IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

ラムダ式で部分適用?

部分的用途とか、ラムダ式とかghci上で、小さなコードをいろいろ試していたらだんだんわからなくなりました。

min関数はパラメータを2つ取ります。Integer型の5を部分適用して、5と比較して小さい値をとる関数を作ります。

Prelude> :t min
min :: Ord a => a -> a -> a
Prelude> let min5 = min 5
Prelude> :t min5
min5 :: Integer -> Integer
Prelude> min5 10
5

ここで、下記を試してみます。(このようにすることの意味はほとんどないですが。。)

Prelude> :t (\x -> min x)
(\x -> min x) :: Ord a => a -> a -> a
Prelude> 
Prelude> :t (\x -> min x ) 5
(\x -> min x ) 5 :: (Num a, Ord a) => a -> a
Prelude> 
Prelude> (\x -> min x) 5 10
5

次に、letを使って関数名を明示的につけてみます。

Prelude> let minlamda = \x -> min x
Prelude> minlamda 5 10

<interactive>:20:10:
    No instance for (Num ()) arising from the literal `5'
    Possible fix: add an instance declaration for (Num ())
    In the first argument of `minlamda', namely `5'
    In the expression: minlamda 5 10
    In an equation for `it': it = minlamda 5 10
Prelude> :t minlamda
minlamda :: () -> () -> ()
Prelude> 

型を確認するとUnit型になっています。

無名関数のときと有名関数のときで挙動が違うように思えます。