为什么ghci不能匹配这种类型?

时间:2017-12-26 10:10:46

标签: haskell

我正在查看following Haskell book - 查看章节Walk the Line

当我在ghci中运行以下代码时:

type Birds = Int  
type Pole = (Birds,Birds)  

x -: f = f x

:{
landLeft :: Birds -> Pole -> Maybe Pole
landLeft n (left,right)
    | abs ((left + n) - right) < 4 = Just (left + n, right)
    | otherwise                    = Nothing
:}

:{
landRight :: Birds -> Pole -> Maybe Pole
landRight n (left,right)
    | abs (left - (right + n)) < 4 = Just (left, right + n)
    | otherwise                    = Nothing
:}

--Failure
(0,0) -: landLeft 1 -: landRight 4 
--(0,0) -: landLeft 1 -: landRight 4 -: landLeft (-1) -: landRight (-2)  
--(0,2)  

我收到错误:

Prelude> (0,0) -: landLeft 1 -: landRight 4 

<interactive>:17:24: error:
    • Couldn't match type ‘Maybe Pole’ with ‘(Birds, Birds)’
      Expected type: Maybe Pole -> Maybe Pole
        Actual type: Pole -> Maybe Pole
    • In the second argument of ‘(-:)’, namely ‘landRight 4’
      In the expression: (0, 0) -: landLeft 1 -: landRight 4
      In an equation for ‘it’: it = (0, 0) -: landLeft 1 -: landRight 4

我的问题是:为什么ghci不能匹配此类型?

1 个答案:

答案 0 :(得分:2)

<div class="parent"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div>一起使用的landLeftlandRight的变体使用-:作为返回类型,而不是Pole。让我们看一下所有类型:

Maybe Pole

由于landLeft 1 :: Pole -> Maybe Pole landRight 4 :: Pole -> Maybe Pole (-:) :: a -> (a -> b ) -> b (0,0) :: Pole (-:) (0,0) :: (Pole -> b ) -> b (-:) (0,0) (landLeft 1) :: Maybe Pole 不是Maybe Pole,我们无法再次Pole使用(-:)。 LYAH展示了如何处理这些功能:您需要一种方法将landRight函数与a -> Maybe b一起使用。这是Maybe a工作:

(>>=)

继续本章,因为作者会立即解决您的问题:

  

当我们在不让皮埃尔失去平衡的情况下降落时,我们会在landLeft 1 (0,0) >>= landRight 4 中找到一根新杆。但当更多的鸟类最终落在极点的一侧时,我们得到Just。这很酷,但是 我们似乎已经失去了在杆子上反复着陆鸟类的能力 。我们不能再Nothing了,因为当我们将landLeft 1 (landRight 1 (0,0))应用于landRight 1时,我们不会获得(0,0),而是PoleMaybe Pole需要landLeft 1而不是Pole。 [强调我的]