首页 > 解决方案 > 如何在 Haskell 中导出组合类型

问题描述

我是 Haskell 的新手。我试图了解类型的组合是如何工作的。

(.) :: (b -> c) -> (a -> b) -> a -> c

fmap :: Functor f => (x -> y) -> f x -> f y
fmap . fmap :: (Functor f1, Functor f2) => (x -> y) -> f1 (f2 x) -> f1 (f2 y)

我如何理解上述类型信息如下。


1. (x -> y) -> f1 x -> f1 y  -- First fmap
      -> (x' -> y') -> f2 x' -> f2 y'  -- Second fmap
2. Compare the (1) with (.) type signature then we get
     In (b -> c)
        b = (x -> y)
        c = f1 x -> f1 y
     In (a -> b)
        a = (x' -> y')
        b = f2 x' -> f2 y'
3. Now the result is a -> c but before that b in (b -> c) should be b in (a -> b)
     (x -> y) === f2 x' -> f2 y'
     That means x = f2 x' & y = f2 y'
4. Result is a -> c
     (x' -> y') -> f1 x -> f1 y
     Substituting (3) results here
     (x' -> y') -> f1 (f2 x') -> f1 (f2 y')
     This is Alpha equivalent to  (x -> y) -> f1 (f2 x) -> f1 (f2 y)

为了测试我的理解,我尝试了各种数据类型,但我很少成功。下面是我无法弄清楚的类型签名。


 f = undefined :: (x -> y -> w -> z -> a) -> g x -> g y
 -- Type of f . f in prelude
 f . f :: (x -> (w1 -> z1 -> a1) -> w2 -> z2 -> a2) -> g (y -> x) -> g y

我对上述方法的处理

1. (x -> y -> w -> z -> a) -> g x -> g y
     -> (x' -> y' -> w' -> z' -> a') -> g' x' -> g' y'
2. Comparing with (.) then 
     In (b -> c)
        b = (x -> y -> w -> z -> a)
        c = g x -> g y
     In (a -> b)
        a = (x' -> y' -> w' -> z' -> a')
        b = g' x' -> g' y'
3. Comparing b from (b -> c) & (a -> b)
     (x -> y -> w -> z -> a) === g' x' -> g' y'
     That means x = g' x'  &  y -> w -> z -> a = g' y'
4. Result is a -> c
     (x' -> y' -> w' -> z' -> a') -> g x -> g y
     Now there is no direct y I can substitute in g y

我看作品的方法不适合我。

标签: haskelltypestype-inferencecompositionfunction-composition

解决方案



推荐阅读