【发布时间】:2017-12-26 10:10:46
【问题描述】:
我正在处理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不能匹配这种类型?
【问题讨论】:
-
Maybe Pole不是Pole。您不能将Maybe Pole传递给需要Pole的东西。 LYAH 很快就会参与其中。 -
感谢@AJFarmar - 这很有帮助。您能否就如何解决这个问题进行扩展?
-
LYAH 会告诉你如何做到这一点,但你可以写
a :- f = a >>= f和写Just (0,0)而不是(0,0)。但再一次,LYAH 很快就会解释这一点。
标签: haskell