Help us understand the problem. What is going on with this article?

Haskellの関数適用($)と関数合成(.)

関数適用($)と関数合成(.)

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)

Thanks!!

zeek0x
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした