Hatena::ブログ(Diary)

かきにっき

2011-12-21

[]Scalaでidを書こうとした

最初,無名関数で書こうとしたら,どうすれば多相的になってくれるのかわからなくて,ぐぐってたら名前を付ければいいということだった.

ところが,

scala> def id[T](x: T) = x
id: [T](x: T)T

scala> id _
res0: Nothing => Nothing = <function1>

scala> (id _)(42)
<console>:9: error: type mismatch;
 found   : Int(42)
 required: Nothing
              (id _)(42)
                     ^

( ゚Д゚)


(追記 12/23 11:59)

scala> ((identity _):Int => Int)(42)
res8: Int = 42

scala> (((identity _):(Int => Int) => (Int => Int))(identity _))(42)
res9: Int = 42

型を書けば動く.手前に書いた場合は推論してくれる.

メソッドは多相的になれるけど関数は多相的になれないのかな.

xuweixuwei 2011/12/23 07:48 実は Predef って自動でimportされるオブジェクトに "identity" っていう名前で入ってますよ

https://github.com/scala/scala/blob/v2.9.1/src/library/scala/Predef.scala#L56

gengargengar 2011/12/23 11:54 気付きませんでした.ありがとうございます.

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証

トラックバック - http://d.hatena.ne.jp/gengar/20111221/1324442511