const function in Haskell

前端 未结 3 941
挽巷
挽巷 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条回答
  •  孤街浪徒
    2020-12-15 17:06

    Chuck is right, function application in Haskell is left associative, meaning that a function invocation like f a b c is equivalent to (((f a) b) c). Remember, in Haskell you should always practice looking at types of functions and trying to infer what a function can and can't do based on its type. At first you might fail to deduce anything from a function type, but with more experience type information will become indispensable.

    What is the type of const? Enter :t const in GHCi. It will return const :: a -> b -> a. a and b are type variables, meaning that const will accept an argument of any type. As 1st and 2nd arguments have different types, you can pass practically everything to the function:

    const 1 2 -- returns 1
    const 'a' 1 -- returns 'a'
    const [1,2,3] "a" -- returns [1,2,3]
    

    There might've been specific typeclass constraints on type variables of const that would prevent passing functions, like Num or Ord, because a function isn't an instance of these typeclasses. In other words, a function doesn't behave as a number or an ordered thing, so f + g or f < g don't make sense. But const has no typeclass constraints that would stop us from passing functions as arguments. Remember that Haskell supports higher-order functions? This means that Haskell's functions can accept and return other functions. Therefore:

    const (+) (*) -- returns (+)
    const head tail -- returns head
    const id 2 -- returns id
    

    const just ignores the 2nd argument and returns whatever was passed as a 1st argument, be it a Char, String, Integer, Maybe, [], some very complex algebraic data type, or even a function.

    If the type of const is a -> b -> a, can you guess the type of const 'a' without finding it out without typing :t const 'a' in GHCi? To find out a type of const 'a', substitute the type of the 1st argument in place of all same type variables, then remove the first argument from the type.

    1. a -> b -> a: original type
    2. Char -> b -> Char: substitute new type in type variables a
    3. b -> Char: the type of a new function by removing the 1st argument from type declaration

    What is the type of const id then?

    1. a -> b -> a: original type
    2. (a -> a) -> b -> (a -> a): substitution
    3. b -> (a -> a): resulting type (first argument removed)
    4. b -> a -> a: same as above, -> operator is right-associative

    Exercise:

    1. Try to figure out mentally or with pen and paper, without using GHCi, what are the types of: const (+), const head, const tail, const (++), const map
    2. Try to find out what arguments would you pass to the above functions to get a concrete value.

提交回复
热议问题