Monday 12 August 2013

Haskell 入門! (12)

合成函数の作り方.今回は短いぜ.

en.wikibooks の haskell より.CC-BY-SA での公開です.



Function composition

関数の合成というかなんというか.普通に g(f(x)) な感じでよろしい.
f x = x + 3
square x = x * x
Prelude> square(f 1)
16
Prelude> square(f 2)
25
Prelude> f (square 1)
4
Prelude> f (square 4)
19
という感じ.
g x = f (square x)
みたいな書き方もできます.
これ,括弧がないと f square を計算しようとして上手く行きません.
関数の合成には特別な書き方もあります: 数学で関数の合成の時に使う記号を模した(.) を使って
g x = (f . square) x
そしてこれは
g  = f . square
と書いても動くがどちらが推奨されてるのかは知らない.

No comments:

Post a Comment