Number of Parameters of a Haskell Function

后端 未结 2 888
别跟我提以往
别跟我提以往 2021-01-19 01:43

When I try to compile this with ghc it complains the number of parameters in the left hand sides of the function definition are different.

modul         


        
相关标签:
2条回答
  • 2021-01-19 02:21

    It's not legal. The restriction is described in the Haskell 2010 Report:

    4.4.3.1 Function bindings

    [...]

    Note that all clauses defining a function must be contiguous, and the number of patterns in each clause must be the same.

    0 讨论(0)
  • 2021-01-19 02:43

    The answer from melpomene is the summation of the syntax rules. In this answer I want to try to describe why this has to be the case.

    From the point of view of the programmer, the syntax in the question seems quite reasonable. There is a first specific case which is marked by a value in the second parameter. Then there is a general solution which reduces to an existing function. Either pattern on its own is valid so why can they not co-exist?

    The syntax rule that all patterns must capture exactly the same parameters is a necessary result of haskell being a lazy language. Being lazy means that the values of parameters are not evaluated until they are needed.

    Let's look at what happens when we curry a function, that is provide it with less then the number of parameters in the declaration. When that happens haskell produces an anonymous function* that will complete the function and stores the first parameters in the scope of that function without evaluating them.

    That last part is important. For functions with different numbers of parameters, it would be necessary to evaluate some of them to choose which pattern to match, but then not evaluate them.

    In other words the compiler needs to know exactly how many parameters it needs before it evaluates them to choose among the patterns. So while it seems like we should not need to put an extra _ in, the compiler needs it to be there.

    As an aside, the order in which parameters occur can make a big difference in how easy a function is to implement and use. See the answers to my question Ordering of parameters to make use of currying for suggestions. If the order is reversed on the example function, it can be implemented with only the one named point.

    from_maybe :: Maybe a -> a -> a
    from_maybe Nothing = id
    from_maybe (Just x) = const x
    

    *: What an implementation like GHC actually does in this situation is subject to optimization and may not work exactly this way, but the end result must be the same as if it did.

    0 讨论(0)
提交回复
热议问题