SlideShare a Scribd company logo
1 of 34
Scalaマクロ入門
アレクセリス アンドレアス(龍ちゃん)Team RegionUp
2017-02-17 株式会社ビズリーチ
Today’s Presentation
• Speaker Introduction → 誰なの、こいつ?
• About Macros in general →「マクロ」って「真黒」のこと?
• Macros in Scala → 何とかimplicit理解できたばかりなのに、
また面倒臭いこと…
• In Action: Code Sample (master branch) → やっと、コードがでて
くる
• Macros in Scala (code explanation) → は!…けど、使う自信がな
いな…
Today’s Presentation
• In Action: Code Sample (cdef_macro branch) → おっと、面白くなってき
たぞ
• (Scala Refresh) Structural Types → 「構造的部分型」<(_ _)>
• (Scala Refresh) Type-classes → 「型クラス」<(_ _)><(_ _)>
• Notes on Reflections: Types, Symbols, Trees → Trees?花粉所の時期
を思い出す…
• Macro specific methods → これってScala???
• Summarizing → やっと終わったみたい。早う飲みに行きたいわ!
• Q&A → ちょ、ちょっと待って!〇〇をどうやるんでしたっけ?
自己紹介
• アレクセリス アンドレアス
• ギリシャ生まれ、日本好き 44歳
• アテネ効果大学電子情報科学部情報学科
• 1997年来日、NAIST情報科学研究科修士課程
• ATR ネットワーク研究所 各員研究員
• 大手メーカーでSE 10年間
• いろいろあって。。。
• 株式会社ビズリーチ2014年5月入社
• 2年前までずっと関西。
m(_ _)mスマン
時間切れで、スライドの殆どは英語のままです。
誠に申し訳ありません。
当然発表は、日本語で
About Macros in General
• What is a macro
• Macro(Macroinstruction): An instruction to the
compiler, to replace one part of the program with a
replacement, created based on a
procedure/template
[
https://en.wikipedia.org/wiki/Macro_(computer_sci
ence) ]
About Macros in General
• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug macro
About Macros in General
• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug macro
• In C language, macro works with text substitution by the pre-compiler
About Macros in General
• Typical example: C preprocessor macros
• In C language, perhaps the most common macro is the debug
macro
• This illustrates the point from the definition we gave before
• In C language, macro works with text substitution by the pre-
compiler
• This also illustrates the problem with this kind of macros
About Macros in General
• This also illustrates the problem with this kind of
macros
About Macros in General
• This also illustrates the problem with this kind of
macros
Macros in Scala
• Experimental feature
• Originally introduced in v.2.10
• Gained a very high rate of adoption.
• Has been in active development/extention ever since
• Currently(2.12), still experimental
• Main researcher/developer behind scalamacros: Eugene Burmako, EPFL
• Resources
http://scalamacros.org/
http://docs.scala-lang.org/overviews/macros/overview.html (邦訳有り)
Macros in Scala
• In contrast to macros in C, Scala macros:
• 1) are written in full-fledged Scala,
• 2) work with expression trees, not with raw strings,
• 3) cannot change syntax of Scala.
• They get expanded at compile time, so they are statically checked, as will be
illustrated later
• Macros are called by the compiler during compilation, so they have access to the
compiler’s API (Compile-time Reflection)
• Using macros relies heavily on understanding Scala reflection
Resource: http://docs.scala-lang.org/overviews/reflection/overview.html
Macros in Scala
• But why do we need macros in the first place?
• [ http://scalamacros.org/paperstalks/2013-07-17-
WhatAreMacrosGoodFor.pdf ]
• Basically:
• Code Generation (& reduction of boilerplate code)
• Static Checks
• Domain-specific languages (DSLs)
• In this talk, we will demonstrate the 1st use
Macros in Scala
• Macros come in many flavors:
• Def macros
• Implicit Materializers
• Type providers
• Macro Annotations
• (still under rigorous extension)
• Here we will introduce the various concepts related to macros by examining types:
• Def macros, as the very very basic case of a macro
• Implicit Materializers, as the real use-case that turned up during work.
In Action: Code Sample
(master branch)
https://github.com/aalexelis/scalaMacro
Nyumon
Macros in Scala
• Macros is an experimental feature, must be imported
• A macro declaration is a method declaration, delegating to a macro
implementation, by the keyword macro
• Macros depend on a Context
• Context is …
• Blackbox / Whitebox contexts
• They bring reflection API into scope by importing universe
• The return type of a macro is of type Tree (AST: Abstract Syntactic Tree)
(more on this later)
Macros in Scala
• At the calling site, a macro invocation is a plain method call
• Macro implementation has to be already compiled when the macro calling code is
being compiled.
• Therefore, to set up SBT for macros we have to structure macro definitions and
macro invocations in separate projects
• Usually macros will need to have access to data structures and interfaces, so it is
better to include them (or make them depend on the “common” subsystem)
• Macro subsystem should declare dependency on scale-reflect module
• For some “more experimental” features, you must install the macro-paradise
compiler plugin
Macros in Scala
• Macro Bundles
• A new (2.11) convention regarding where to allocate the implementation
of a macro
• Before, macro implementation was represented as a function inside
an object it was declared
• With macro bundles, implementation can be a method in a trait that
extends the Macro trait, separately from the declaration site
• This has several advantages, mostly regarding modularity of the code,
and scope visibility
Macros in Scala
• Macro Bundles
Macros in Scala
• Quasiquotes
• A new (2.11) way to define AST using string interpolation
• Before, AST had to be created “by hand”, from the basic
API elements provided by the reflection API
• With Quasiquotes, we can interpolate variables inside a
string that looks exactly how we want the macro
expansion to be
Macros in Scala
• Quasiquotes
Macros in Scala
• Quasiquotes
• They can be used for pattern matching too, which
is very convenient
• Although the concept looks simple, its
implementation is probably complex, so the
scalamacros people warn that there might be still
residual bugs. In such case we have to resort
back to writing the AST by hand.
In Action: Code Sample
(cdef_macro branch)
https://github.com/aalexelis/scalaMacroNyum
on/tree/cdefext_macro
Typeclass
• A typeclass is a sort of interface that defines some
behavior. If a type is a part of a typeclass, that
means that it supports and implements the behavior
the typeclass describes.
• It means “in order to perform this operation in a
meaningful way, the type of the instance or
argument must be a member of the type class
Type Classes
• The idea of typeclasses is that you provide evidence
that a class satisfies an interface
• Instead of having the type directly implement the
interface, I can provide the implementation
elsewhere in the code
• This allow us avoid the inheritance spaghetti of
unrelated classes, and allows us to use different
libraries uniformly.
Notes on Reflection
• Reflection: the possibility that a program can have access, inspect and manipulate it’s
own representation
• Usually reflection is a “run-time” tool
• However、 Scala allows for a “compile-time” type of reflection, via macros
• They are based on the same api with the run-time reflection, which allows code
sharing
• Reflection Environment
• Universe: the environment info for current use of reflection
• Mirror: the parts we have access to reflectively
Notes on Reflection:
Types
• Types
• Types represent information about the type of a corresponding
symbol.
• They are available to the compiler, to be able to produce the
proper implementation of the program
• In general, they are erased after the type checking part of the
compilation is done
• However, when using reflections, we need access to type
information, in order to manipulate the entities properly.
Notes on Reflection:
TypeTags
• TypeTags: what are they?
• They are a type of manifest, of all the information the compiler knows
about a specific type
• They can be passed as parameters to methods, and used to extract type
information related to the manipulated entities
• In Scala reflection there are 3 types of TypeTags
• TypeTags
• WeakTypeTags
• ClassTags
Notes on Reflection: Symbols
• Symbols
• Symbols bind entities to names, so that we can refer to them. Whatever you can name in
Scala gets an associated Symbol
• TypeSymbol: symbol for a type in general
• ClassSymbol: symbol for a class or trait
• TermSymbol: symbol for val, var, def, object, package, value parameters
• MethodSymbol: symbol for methods
• ModuleSymbol: symbol for object declarations
• NoSymbol: top level symbol owner, (something like Nil for symbols)
• Free Symbols (@ look at reification for more info)
Notes on Reflection:
Trees
• Trees: abstract syntax trees (ASTs) represent programs
• Annotations
• reify
• Macros
• Subcategories of Trees: trees are made up of nodes
• TermTree: represent terms: Apply nodes for method invocations, New nodes for instantiations
etc.
• TypTree: represent types: ???
• SymTree: represent definitions: ClassDef for definition of class,, ValDef for definition of val, etc
• …some other type of short-lived tree types also exist
Macro Specific methods
• reify: creates Expr with trees
• splice: inserts a subtree into a tree
Summarizing
Thank you for your kind attention.
I will be glad to take questions
→ お手柔らかに <(_ _)>

More Related Content

What's hot

Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with javaHawkman Academy
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSteve Fort
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Rubykim.mens
 
8 oo approach&uml-23_feb
8 oo approach&uml-23_feb8 oo approach&uml-23_feb
8 oo approach&uml-23_febRaj Shah
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsAashish Jain
 

What's hot (15)

Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
Java
JavaJava
Java
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
Akka Actors
Akka ActorsAkka Actors
Akka Actors
 
Core Java
Core JavaCore Java
Core Java
 
8 oo approach&uml-23_feb
8 oo approach&uml-23_feb8 oo approach&uml-23_feb
8 oo approach&uml-23_feb
 
Jvm2
Jvm2Jvm2
Jvm2
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 

Similar to Scalaマクロ入門 bizr20170217

What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!scalaconfjp
 
What's a macro?: Learning by Examples
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Exampleschibochibo
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...Jose Quesada (hiring)
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark Summit
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"Kazuhiro Sera
 
Mel for beginners
Mel for beginnersMel for beginners
Mel for beginnerskedar nath
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure DataTaro L. Saito
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprisesMike Slinn
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala MacrosKnoldus Inc.
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 

Similar to Scalaマクロ入門 bizr20170217 (20)

What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
What's a macro?: Learning by Examples
What's a macro?: Learning by ExamplesWhat's a macro?: Learning by Examples
What's a macro?: Learning by Examples
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
 
Mel for beginners
Mel for beginnersMel for beginners
Mel for beginners
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
10-DesignPatterns.ppt
10-DesignPatterns.ppt10-DesignPatterns.ppt
10-DesignPatterns.ppt
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Scala adoption by enterprises
Scala adoption by enterprisesScala adoption by enterprises
Scala adoption by enterprises
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 

More from dcubeio

AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」
AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」
AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」dcubeio
 
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料dcubeio
 
ビットコインとブロックチェーンを初めからていねいに(超基礎編)
ビットコインとブロックチェーンを初めからていねいに(超基礎編)ビットコインとブロックチェーンを初めからていねいに(超基礎編)
ビットコインとブロックチェーンを初めからていねいに(超基礎編)dcubeio
 
20171206 d3 health_tech発表資料
20171206 d3 health_tech発表資料20171206 d3 health_tech発表資料
20171206 d3 health_tech発表資料dcubeio
 
Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話dcubeio
 
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)dcubeio
 
BizReach x Marketo連携
BizReach x Marketo連携BizReach x Marketo連携
BizReach x Marketo連携dcubeio
 
Kinesis Firehoseを使ってみた
Kinesis Firehoseを使ってみたKinesis Firehoseを使ってみた
Kinesis Firehoseを使ってみたdcubeio
 
Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】dcubeio
 
春の脆弱性祭り 2017/06/13
春の脆弱性祭り 2017/06/13春の脆弱性祭り 2017/06/13
春の脆弱性祭り 2017/06/13dcubeio
 
DynamoDBを導入した話
DynamoDBを導入した話DynamoDBを導入した話
DynamoDBを導入した話dcubeio
 
Play2 scalaを2年やって学んだこと
Play2 scalaを2年やって学んだことPlay2 scalaを2年やって学んだこと
Play2 scalaを2年やって学んだことdcubeio
 
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー!
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー! すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー!
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー! dcubeio
 
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料dcubeio
 
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜dcubeio
 
【freee】プロダクトマネージャーの仕事と魅力
【freee】プロダクトマネージャーの仕事と魅力【freee】プロダクトマネージャーの仕事と魅力
【freee】プロダクトマネージャーの仕事と魅力dcubeio
 
【ビズリーチ】プロダクトマネージャーの仕事と魅力
【ビズリーチ】プロダクトマネージャーの仕事と魅力【ビズリーチ】プロダクトマネージャーの仕事と魅力
【ビズリーチ】プロダクトマネージャーの仕事と魅力dcubeio
 
Python × Herokuで作る 雑談slack bot
Python × Herokuで作る 雑談slack botPython × Herokuで作る 雑談slack bot
Python × Herokuで作る 雑談slack botdcubeio
 
HR Tech x 機械学習 導入事例紹介
HR Tech x 機械学習 導入事例紹介HR Tech x 機械学習 導入事例紹介
HR Tech x 機械学習 導入事例紹介dcubeio
 
機械学習を支えるX86 64の拡張命令セットを読む会 20170212
機械学習を支えるX86 64の拡張命令セットを読む会 20170212機械学習を支えるX86 64の拡張命令セットを読む会 20170212
機械学習を支えるX86 64の拡張命令セットを読む会 20170212dcubeio
 

More from dcubeio (20)

AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」
AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」
AWS Summit Tokyo 2019登壇資料「DevOpsの劇的改善!古いアーキテクチャから王道のマネージドサービスを活用しフルリプレイス! 」
 
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
 
ビットコインとブロックチェーンを初めからていねいに(超基礎編)
ビットコインとブロックチェーンを初めからていねいに(超基礎編)ビットコインとブロックチェーンを初めからていねいに(超基礎編)
ビットコインとブロックチェーンを初めからていねいに(超基礎編)
 
20171206 d3 health_tech発表資料
20171206 d3 health_tech発表資料20171206 d3 health_tech発表資料
20171206 d3 health_tech発表資料
 
Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話Go初心者がGoでコマンドラインツールの作成に挑戦した話
Go初心者がGoでコマンドラインツールの作成に挑戦した話
 
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)
初めての Raspberry pi 〜プラレールをunityの世界の中で走らせよう〜 (1)
 
BizReach x Marketo連携
BizReach x Marketo連携BizReach x Marketo連携
BizReach x Marketo連携
 
Kinesis Firehoseを使ってみた
Kinesis Firehoseを使ってみたKinesis Firehoseを使ってみた
Kinesis Firehoseを使ってみた
 
Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】Apiドキュメンテーションツールを使いこなす【api blueprint編】
Apiドキュメンテーションツールを使いこなす【api blueprint編】
 
春の脆弱性祭り 2017/06/13
春の脆弱性祭り 2017/06/13春の脆弱性祭り 2017/06/13
春の脆弱性祭り 2017/06/13
 
DynamoDBを導入した話
DynamoDBを導入した話DynamoDBを導入した話
DynamoDBを導入した話
 
Play2 scalaを2年やって学んだこと
Play2 scalaを2年やって学んだことPlay2 scalaを2年やって学んだこと
Play2 scalaを2年やって学んだこと
 
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー!
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー! すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー!
すごーい!APIドキュメントを更新するだけでAPIが自動テストできちゃう!たのしー!
 
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
20170329 D3 DBAが夜間メンテをしなくなった日 発表資料
 
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜
Bitcoin x Slack でマイクロペイメントを実現! 〜生活の必要上割り勘botを作るまで〜
 
【freee】プロダクトマネージャーの仕事と魅力
【freee】プロダクトマネージャーの仕事と魅力【freee】プロダクトマネージャーの仕事と魅力
【freee】プロダクトマネージャーの仕事と魅力
 
【ビズリーチ】プロダクトマネージャーの仕事と魅力
【ビズリーチ】プロダクトマネージャーの仕事と魅力【ビズリーチ】プロダクトマネージャーの仕事と魅力
【ビズリーチ】プロダクトマネージャーの仕事と魅力
 
Python × Herokuで作る 雑談slack bot
Python × Herokuで作る 雑談slack botPython × Herokuで作る 雑談slack bot
Python × Herokuで作る 雑談slack bot
 
HR Tech x 機械学習 導入事例紹介
HR Tech x 機械学習 導入事例紹介HR Tech x 機械学習 導入事例紹介
HR Tech x 機械学習 導入事例紹介
 
機械学習を支えるX86 64の拡張命令セットを読む会 20170212
機械学習を支えるX86 64の拡張命令セットを読む会 20170212機械学習を支えるX86 64の拡張命令セットを読む会 20170212
機械学習を支えるX86 64の拡張命令セットを読む会 20170212
 

Recently uploaded

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 

Recently uploaded (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 

Scalaマクロ入門 bizr20170217

  • 2. Today’s Presentation • Speaker Introduction → 誰なの、こいつ? • About Macros in general →「マクロ」って「真黒」のこと? • Macros in Scala → 何とかimplicit理解できたばかりなのに、 また面倒臭いこと… • In Action: Code Sample (master branch) → やっと、コードがでて くる • Macros in Scala (code explanation) → は!…けど、使う自信がな いな…
  • 3. Today’s Presentation • In Action: Code Sample (cdef_macro branch) → おっと、面白くなってき たぞ • (Scala Refresh) Structural Types → 「構造的部分型」<(_ _)> • (Scala Refresh) Type-classes → 「型クラス」<(_ _)><(_ _)> • Notes on Reflections: Types, Symbols, Trees → Trees?花粉所の時期 を思い出す… • Macro specific methods → これってScala??? • Summarizing → やっと終わったみたい。早う飲みに行きたいわ! • Q&A → ちょ、ちょっと待って!〇〇をどうやるんでしたっけ?
  • 4. 自己紹介 • アレクセリス アンドレアス • ギリシャ生まれ、日本好き 44歳 • アテネ効果大学電子情報科学部情報学科 • 1997年来日、NAIST情報科学研究科修士課程 • ATR ネットワーク研究所 各員研究員 • 大手メーカーでSE 10年間 • いろいろあって。。。 • 株式会社ビズリーチ2014年5月入社 • 2年前までずっと関西。
  • 6. About Macros in General • What is a macro • Macro(Macroinstruction): An instruction to the compiler, to replace one part of the program with a replacement, created based on a procedure/template [ https://en.wikipedia.org/wiki/Macro_(computer_sci ence) ]
  • 7. About Macros in General • Typical example: C preprocessor macros • In C language, perhaps the most common macro is the debug macro
  • 8. About Macros in General • Typical example: C preprocessor macros • In C language, perhaps the most common macro is the debug macro • In C language, macro works with text substitution by the pre-compiler
  • 9. About Macros in General • Typical example: C preprocessor macros • In C language, perhaps the most common macro is the debug macro • This illustrates the point from the definition we gave before • In C language, macro works with text substitution by the pre- compiler • This also illustrates the problem with this kind of macros
  • 10. About Macros in General • This also illustrates the problem with this kind of macros
  • 11. About Macros in General • This also illustrates the problem with this kind of macros
  • 12. Macros in Scala • Experimental feature • Originally introduced in v.2.10 • Gained a very high rate of adoption. • Has been in active development/extention ever since • Currently(2.12), still experimental • Main researcher/developer behind scalamacros: Eugene Burmako, EPFL • Resources http://scalamacros.org/ http://docs.scala-lang.org/overviews/macros/overview.html (邦訳有り)
  • 13. Macros in Scala • In contrast to macros in C, Scala macros: • 1) are written in full-fledged Scala, • 2) work with expression trees, not with raw strings, • 3) cannot change syntax of Scala. • They get expanded at compile time, so they are statically checked, as will be illustrated later • Macros are called by the compiler during compilation, so they have access to the compiler’s API (Compile-time Reflection) • Using macros relies heavily on understanding Scala reflection Resource: http://docs.scala-lang.org/overviews/reflection/overview.html
  • 14. Macros in Scala • But why do we need macros in the first place? • [ http://scalamacros.org/paperstalks/2013-07-17- WhatAreMacrosGoodFor.pdf ] • Basically: • Code Generation (& reduction of boilerplate code) • Static Checks • Domain-specific languages (DSLs) • In this talk, we will demonstrate the 1st use
  • 15. Macros in Scala • Macros come in many flavors: • Def macros • Implicit Materializers • Type providers • Macro Annotations • (still under rigorous extension) • Here we will introduce the various concepts related to macros by examining types: • Def macros, as the very very basic case of a macro • Implicit Materializers, as the real use-case that turned up during work.
  • 16. In Action: Code Sample (master branch) https://github.com/aalexelis/scalaMacro Nyumon
  • 17. Macros in Scala • Macros is an experimental feature, must be imported • A macro declaration is a method declaration, delegating to a macro implementation, by the keyword macro • Macros depend on a Context • Context is … • Blackbox / Whitebox contexts • They bring reflection API into scope by importing universe • The return type of a macro is of type Tree (AST: Abstract Syntactic Tree) (more on this later)
  • 18. Macros in Scala • At the calling site, a macro invocation is a plain method call • Macro implementation has to be already compiled when the macro calling code is being compiled. • Therefore, to set up SBT for macros we have to structure macro definitions and macro invocations in separate projects • Usually macros will need to have access to data structures and interfaces, so it is better to include them (or make them depend on the “common” subsystem) • Macro subsystem should declare dependency on scale-reflect module • For some “more experimental” features, you must install the macro-paradise compiler plugin
  • 19. Macros in Scala • Macro Bundles • A new (2.11) convention regarding where to allocate the implementation of a macro • Before, macro implementation was represented as a function inside an object it was declared • With macro bundles, implementation can be a method in a trait that extends the Macro trait, separately from the declaration site • This has several advantages, mostly regarding modularity of the code, and scope visibility
  • 20. Macros in Scala • Macro Bundles
  • 21. Macros in Scala • Quasiquotes • A new (2.11) way to define AST using string interpolation • Before, AST had to be created “by hand”, from the basic API elements provided by the reflection API • With Quasiquotes, we can interpolate variables inside a string that looks exactly how we want the macro expansion to be
  • 22. Macros in Scala • Quasiquotes
  • 23. Macros in Scala • Quasiquotes • They can be used for pattern matching too, which is very convenient • Although the concept looks simple, its implementation is probably complex, so the scalamacros people warn that there might be still residual bugs. In such case we have to resort back to writing the AST by hand.
  • 24. In Action: Code Sample (cdef_macro branch) https://github.com/aalexelis/scalaMacroNyum on/tree/cdefext_macro
  • 25. Typeclass • A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. • It means “in order to perform this operation in a meaningful way, the type of the instance or argument must be a member of the type class
  • 26. Type Classes • The idea of typeclasses is that you provide evidence that a class satisfies an interface • Instead of having the type directly implement the interface, I can provide the implementation elsewhere in the code • This allow us avoid the inheritance spaghetti of unrelated classes, and allows us to use different libraries uniformly.
  • 27. Notes on Reflection • Reflection: the possibility that a program can have access, inspect and manipulate it’s own representation • Usually reflection is a “run-time” tool • However、 Scala allows for a “compile-time” type of reflection, via macros • They are based on the same api with the run-time reflection, which allows code sharing • Reflection Environment • Universe: the environment info for current use of reflection • Mirror: the parts we have access to reflectively
  • 28. Notes on Reflection: Types • Types • Types represent information about the type of a corresponding symbol. • They are available to the compiler, to be able to produce the proper implementation of the program • In general, they are erased after the type checking part of the compilation is done • However, when using reflections, we need access to type information, in order to manipulate the entities properly.
  • 29. Notes on Reflection: TypeTags • TypeTags: what are they? • They are a type of manifest, of all the information the compiler knows about a specific type • They can be passed as parameters to methods, and used to extract type information related to the manipulated entities • In Scala reflection there are 3 types of TypeTags • TypeTags • WeakTypeTags • ClassTags
  • 30. Notes on Reflection: Symbols • Symbols • Symbols bind entities to names, so that we can refer to them. Whatever you can name in Scala gets an associated Symbol • TypeSymbol: symbol for a type in general • ClassSymbol: symbol for a class or trait • TermSymbol: symbol for val, var, def, object, package, value parameters • MethodSymbol: symbol for methods • ModuleSymbol: symbol for object declarations • NoSymbol: top level symbol owner, (something like Nil for symbols) • Free Symbols (@ look at reification for more info)
  • 31. Notes on Reflection: Trees • Trees: abstract syntax trees (ASTs) represent programs • Annotations • reify • Macros • Subcategories of Trees: trees are made up of nodes • TermTree: represent terms: Apply nodes for method invocations, New nodes for instantiations etc. • TypTree: represent types: ??? • SymTree: represent definitions: ClassDef for definition of class,, ValDef for definition of val, etc • …some other type of short-lived tree types also exist
  • 32. Macro Specific methods • reify: creates Expr with trees • splice: inserts a subtree into a tree
  • 34. Thank you for your kind attention. I will be glad to take questions → お手柔らかに <(_ _)>