Haskell: Function application with $

后端 未结 4 1706
滥情空心
滥情空心 2021-01-11 15:00

In the following snippet, you can see my two collatz functions I wrote in Haskell. For the recursive application I used parentheses in the first example (collatz) to get the

4条回答
  •  我在风中等你
    2021-01-11 15:26

    Since others have explained what the problem is, I figured I'll explain how you could have figured this out on your own. (Teaching a man to fish and so on...)

    Note this part of the error message:

    In the first argument of '($)', namely 'n : collatz''

    That's the clue to noticing that this is a precedence problem. GHC is telling you that n : collatz' was parsed as the first argument of $, while you were expecting the first argument to be just collatz'.

    At this point, I usually fire up GHCi and check the precedences involved using the :info command:

    > :info :
    data [] a = ... | a : [a]   -- Defined in GHC.Types
    infixr 5 :
    > :info $
    ($) :: (a -> b) -> a -> b   -- Defined in GHC.Base
    infixr 0 $
    

    It says that the precendence of : is 5, while the precedence of $ is 0, which explains why the : is binding "tighter" than the $.

提交回复
热议问题