Chuck is right , the function application in Haskell is left associative , which means that calling a function like fabc is equivalent to (((fa) b) c) . Remember that in Haskell you should always practice regarding function types and try to conclude that a function can and cannot do based on its type. At first, you can deduce nothing from the type of function, but with more information about the type of experience 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 , which means that const will accept an argument of any type. Since the arguments 1 st and 2 nd are of different types, you can pass almost all functions:
const 1 2 -- returns 1 const 'a' 1 -- returns 'a' const [1,2,3] "a" -- returns [1,2,3]
Perhaps there were special restrictions on type types in const variables that would prevent the transfer of functions such as Num or Ord , because the function is not an instance of these types. In other words, the function does not behave like a number or an ordered thing, so f + g or f < g does not make sense. But const has no stack type restrictions that would prevent us from passing functions as arguments. Remember that Haskell supports higher-order functions ? This means that Haskell functions can accept and return other functions. Therefore:
const (+) (*) -- returns (+) const head tail -- returns head const id 2 -- returns id
const simply ignores the argument 2 nd and returns everything that was passed as argument 1 st, whether it be Char, String, Integer, Maybe, [], some very complex type of algebraic data or even a function.
If the type of const is a -> b -> a , can you guess the type of const 'a' without discovering it without typing :t const 'a' in GHCi? To find out the type const 'a' , replace the argument type with 1 st instead of all variables of the same type, then remove the first argument from this type.
a -> b -> a : original typeChar -> b -> Char : replace the new type with variables of type ab -> Char : type of the new function by removing the 1st argument from the type declaration
What is the type of const id then?
a -> b -> a : original type(a -> a) -> b -> (a -> a) : wildcardb -> (a -> a) : result type (first argument removed)b -> a -> a : same as above, operator -> right-associative
The exercise:
- Try to find mentally either pen and paper without using GHCi, what are the types:
const (+) , const head , const tail , const (++) , const map - Try to figure out which arguments you will go to the above functions to get a specific value.
Mirzhan Irkegulov Feb 23 '15 at 15:32 2015-02-23 15:32
source share