const function in Haskell

前端 未结 3 928
挽巷
挽巷 2020-12-15 16:48

The function const is defined in Prelude as:

const x _ = x

In GHCi, when I tried

Prelude> const 6 5  ->          


        
3条回答
  •  萌比男神i
    2020-12-15 17:09

    Functions can also be parameters to other functions. id becomes a parameter of const.

    What the expression (const id 6) 5 really does is:

    (const id 6) 5

    (const id _) 5 -- grab the first parameter id

    id 5

    5

    For more detail about what operators really do:

    1. Anything in a pair of brackets would be treated as a whole expression (but it doesn't mean it will be calculated first). For example: (map (1+) ), (\x -> (-) x )

    2. Prefix operators bind stronger than infix operators

    3. The left-most prefix operator in an expression would be treated as a function which grabs parameters (including other prefix operators) in an expression from left to right until facing infix operators or the end of line. For example, if you type map (+) id 3 const + 2 in GHCi, you will get an error that says "The function `map' is applied to four arguments..." because map grabs (+), id, 3 and const as parameters before the infix operator +.

提交回复
热议问题