[关闭]
@weixin 2014-10-03T04:43:55.000000Z 字数 1662 阅读 1268

how to do type infer in haskell

haskell


Haskell: how to infer the type of an expression manually - Stack Overflow
syntax - Dot Operator in Haskell: need more explanation - Stack Overflow
syntax - What does a fullstop or period or dot (.) mean in Haskell? - Stack Overflow

how to infer the type

how about head.filter fst

  1. *Main> :t filter
  2. filter :: (a -> Bool) -> [a] -> [a]
  3. *Main> :t head
  4. head :: [a] -> a
  5. *Main> :t fst
  6. fst :: (a, b) -> a
  7. *Main> :t (.)
  8. (.) :: (b -> c) -> (a -> b) -> a -> c

type are infered by using 'unification'. what is Unification , need more learning?

started from filter fst :

  1. the first argument for filter is (a->Bool), fst would be unifed with it. How to do it?

(a->Bool) U (a',b') -> a' , which means a => (a', b') , Bool => a' , then we get

  1. a = (Bool, b')
  2. a' = Bool

also, we got filter fst :: [a] -> [a], we can get `filter fst :: [(Bool, b')] -> [(Bool, b')]

  1. then head . [(Bool,b')] -> [(Bool,b')], you can rewrite it as . head [(Bool, b')] ->[(Bool,b')], then

    1. ` (b -> c ) U [a1] -> a1`, we can get `c :: a1, b :: [a1]` ( using a1 is more clear and avoid confusion)
    
    2.  `(a -> b) U [(Bool, b')] -> [(Bool, b')] ` , we can get  `  b :: [(Bool, b')] , a :: [(Bool, b')]`
    
    3.   b is a list of c and b is [(Bool,b')],  so  `c :: (Bool, b')`
    
    4.  so ` . head filter fst :: a -> c ` we got  it is type `a -> c :: [(Bool, b')] -> (Bool, b')` . 
    

how about const 7 (const 3)

  1. *Main> :t const
  2. const :: a -> b -> a

const 3 is what ? we can get a :: 3, in fact a :: Num , ==> const 3 :: (Num a ) => b -> a

so const 7 :: (Num a' ) => b' -> a', then we get const 7 (const 3 ) would be b' U b->a, the we can

get const 7 (const 3 ) :: a' , a' :: Num . so const 7 ( const 3 ) :: (Num a ) => a

how about const 7 const

`const 7 :: (Num a0) => b0 -> a0, b could be anything

cosnt :: a->b->a

then b0 :: a->b->a, so const 7 const :: (Num a0) => a0

how about const (const 3 ) 7

const :: a->b->a

const 3 :: (Num a0) => b0->a0

get a :: (b0->a0), so const (const 3 ) :: b -> a => b -> b0 -> a0, notice a0 is Num

finally we got (Num a ) => b -> b1 -> a

notice, b and b1 could be any time, as an proof, I did some test

  1. *Main> const (const 3) 7 8
  2. 3
  3. *Main> const (const 3) (const 7) 8
  4. 3
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注