社内勉強会の資料をちょっと改変したやつ。 メタプロ & scala.metaの入門編。 メタプログラミングとは プログラミング技法の一種で、ロジックを直接コーディングするのではなく、あるパターンをもったロジックを生成する高位ロジックによってプログラミングを行う方法、またその高位ロジックを定義する方法のこと。 メタプログラミング - wikipedia つまり プログラムを引数としてプログラムを出力とする関数、みたいなもの。 リフレクションも一種のメタプログラミングで、文字列から実行時のオブジェクトに干渉できる。 マクロはプログラムを自動で生成するための仕組み。 内部DSLもある種のメタプログラミングといえる。 参考:StackOverFlow Conclusion: Meta-programming is the ability for a program to reason about
練習を兼ねて、scala.metaを使って普通のclassをcase classに進化させるライブラリを作った。 case classにすると自動で生成される以下のメソッド群をscalametaで模倣している。 toString copy equals apply unapply hashCodeはめんどくさいのでスキップ…。 @Case class Hoge(val n: Int) とか書くとだいたい case class Hoge(n: Int) と同じ感じになる、ということ。 使い方 mavenにあげているので、依存の追加は簡単。 libraryDependencies += "net.petitviolet" %% "acase" % "<latest-version>" でもマクロを有効にするための設定がいろいろ必要となる。 手順はここに書いた。setup これがどれくらい必要な
Scalaのマクロには、ある程度複雑なマクロを書こうとしたときに立ちはだかる壁があります。それがsymbolとownerです。この壁の厄介なところは、ほぼ確実に引っかかる罠でありながら英語も含めてドキュメントがほぼゼロという点です。これについて簡単に解説したいと思います。 Symbol Scalaのマクロにはsymbolという概念があります。12 Symbolは、変数・メソッド・クラスなどの識別子同士を区別したり、メンバ等のメタ情報へのアクセスを仲介したりするために使われます。Cの字句マクロやLispの構文マクロなどにおいては名前被り・名前空間の汚染等を防ぐこと、一言で言うとhygiene性が大きな問題となっていますが、Scalaのマクロにおいては同様の問題は起きにくくなっています。3 なぜなら、Scalaのtyper(より厳密にいうとnamer)が各定義・参照の構文木に適切なsymbol
前回は、Scalaのリフレクションを使う際の、簡単な導入について書きました。今度は、実際にReflection APIを使用して、Scalaのクラスやメソッドから情報を取得していく方法を書いていきたいと思います。 これまでに書いたエントリのまとめは、こちらです。 導入編 http://d.hatena.ne.jp/Kazuhira/20130730/1375192075 定義情報取得編 - 1 http://d.hatena.ne.jp/Kazuhira/20130801/1375370390 定義情報取得編 - 2 http://d.hatena.ne.jp/Kazuhira/20130803/1375526971 インスタンス操作編 http://d.hatena.ne.jp/Kazuhira/20130804/1375604912 オマケ http://d.hatena.ne.jp/
Scalaのマクロというより、一般的にマクロに共通する基本であり重要な部分です。それをScala使って説明するだけです。 Scalaのマクロは、未だexperimentalという位置づけで、他の機能に比べれば仕様やAPIが変わりやすい状態です。そして、機能が搭載されてからあまり時間が経っていないこともあって*1あまり一般的に使われているとはいえない状態でしょう。しかし、Cなどのマクロとは違い、Scalaのものはある程度は本格的にコンパイル時に抽象構文木を自由にいじれるものであり、使いこなせるようになってくるとなかなかおもしろいです。 マクロというと、ある程度の人はLispを思い浮かべると思いますが(?)、先ほど書いた「本格的に抽象構文木いじれる」という点はまさにLispと共通する部分もあります(もちろん異なる部分も多くあります)。 つまり、これから説明することは、On Lisp*2 On
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く