関数適用($)と関数合成(.)
Haskell の関数適用($)と関数合成(.)の操作上の違いを端的に説明
ghci> sum . replicate 5 $ max 6.7 8.9
44.5
ghci> sum $ replicate 5 $ max 6.7 8.9
44.5
- 演算の優先順位は
.
>$
-
.
は右側に関数がくる -
$
は右側に値がくる
従って以下は上記の例と等価
ghci> (sum . replicate 5) $ max 6.7 8.9
44.5
ghci> sum $ (replicate 5 $ max 6.7 8.9)
44.5
以下の例は当然エラーになる
-- .の右側が値なのでエラー
ghci> sum $ replicate 5 . max 6.7 8.9
<interactive>:132:1: error:
* Non type-variable argument in the constraint: Foldable ((->) a1)
(Use FlexibleContexts to permit this)
* When checking the inferred type
it :: forall a1 a2.
(Foldable ((->) a1), Ord (a1 -> a2), Fractional (a1 -> a2),
Num [a2]) =>
[a2]
-- $の右側が関数なのでエラー
ghci> (sum $ replicate 5) $ max 6.7 8.9
<interactive>:137:8: error:
* Couldn't match type `[a0]' with `Double -> t'
Expected type: a0 -> Double -> t
Actual type: a0 -> [a0]
* Possible cause: `replicate' is applied to too many arguments
In the second argument of `($)', namely `replicate 5'
In the expression: (sum $ replicate 5)
In the expression: (sum $ replicate 5) $ max 6.7 8.9
* Relevant bindings include it :: t (bound at <interactive>:137:1)
-- .の右側が値なのでエラー
ghci> sum . (replicate 5 $ max 6.7 8.9)
<interactive>:133:8: error:
* Couldn't match expected type `a -> [c]'
with actual type `[Double]'
* In the second argument of `(.)', namely
`(replicate 5 $ max 6.7 8.9)'
In the expression: sum . (replicate 5 $ max 6.7 8.9)
In an equation for `it': it = sum . (replicate 5 $ max 6.7 8.9)
* Relevant bindings include
it :: a -> c (bound at <interactive>:133:1)