初日ということでIdentityから。
Identityの説明だけれど型クラスに関連するもの(===とか|+|とかほとんどの関数)やScalazのデータ構造(Validation,LazyTupleなど)に関するものは取り扱わないです。
後日EqualやSemigroup,Validationなどを説明するときに出てきます。
Identityは型パラメータAをとり、def value: Aという未定義の関数を持ちます。
パラメータAに様々な関数を提供するコンテナと考えてよいでしょう。
Identitys
IdentitysのmkIdentityによって全ての値はIdentityに暗黙の型変換することができます。
また、unMkIdentityによりIdentityをもとの値に戻すことも可能です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val i: Identity[Int] = 1 | |
val a: Int = i |
unitalという謎のIdentity[Unit]が定義されているけど何に利用するかは不明。
Identity
??
簡単に言うとnullチェック。
nullだった場合は引数で与えた値が返る。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"Scalaz" ?? "Scalaちゃん" assert_=== "Scalaz" | |
(null: String) ?? "Scalaちゃん" assert_=== "Scalaちゃん" |
|>
関数に呼び出し側の値を適用する関数。
ちょっと意味がわからない、コードを見ましょう。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 |> (_ + 1) assert_=== 2 | |
1 |> Option.apply assert_=== Some(1) |
some, left, right, pair, squared
ある型に包む関数。
pairとsquaredは値のペアをタプルで返す。
def squared = pairみたいな定義だけどいるんですかこれ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.some assert_=== Some(1) | |
1.right[String] assert_=== Right(1) | |
"Scalaちゃん".left[Int] assert_=== Left("Scalaちゃん") | |
"ゲソ".pair.assert_===(("ゲソ", "ゲソ")) | |
"ゲソ".pair assert_=== "ゲソ".squared |
doWhile, whileDo
名前通りの関数。
関数と述語を渡す。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.whileDo(_ + 1, _ < 10) assert_=== 10 | |
"Scala".doWhile({ s => println(s); readLine }, _ != "Scalaz") assert_=== "Scalaz" |
Scalazの型クラス、データ構造に関するものを抜くとこれだけ。
これだけではScalazの便利さがわからないと思うので、ぜひ続きも見て下さい!
> unitalという謎のIdentity[Unit]が定義されているけど何に利用するかは不明。
返信削除Identity[Unit] 型のオブジェクトって、1つでよくていくつも生成されても無駄だから、どうせならライブラリ側で用意してvalで束縛しておいたほうがいいんじゃなイカ ?
っていう配慮だろうか・・・?
なるほど、それもそうですね。
返信削除しかし、unitalの使い道とは一体・・・・・