2017-12-26 20 views
0

私はfollowing Haskell bookて働いている - 章Walk the Lineを見て:私はGHCiの中で、次のコードを実行すると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 

私の質問is:ghciがこのタイプにマッチしないのはなぜですか?

+1

'たぶんPole'は' Pole'ではありません。 'ポール'を取るものに 'ポール'を渡すことはできません。 LYAHはすぐにこれに入るつもりです。 – AJFarmar

+0

ありがとう@AJFarmar - それは役立ちます。これをどのように解決できるかという点でそれを拡大できますか? – hawkeye

+0

LYAHはこれを行う方法を教えてくれますが、 'a:-f = a >> = f'と書くことができ、'(0,0) 'の代わりに' Just(0,0) 'と書くことができます。しかし、もう一度、LYAHはこれをすぐに説明しようとしています。 – AJFarmar

答えて

2

戻り値の型ではなく、Maybe Poleとして-:使用Poleと連携landLeftlandRightの変種。のは、もののすべての種類を表示してみましょう:

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 PolePoleではないので、我々はlandRightのために再び(-:)を使用することはできません。 LYAHはこれらの機能をどのように処理するかを示しています。の機能をMaybe aと使用する方法が必要です。それは(>>=)仕事です:著者はすぐに問題に取り組むよう

landLeft 1 (0,0) >>= landRight 4 

は、章を続行:

When we land birds without throwing Pierre off balance, we get a new pole wrapped in a Just . But when many more birds end up on one side of the pole, we get a Nothing . This is cool, but we seem to have lost the ability to repeatedly land birds on the pole. We can't do landLeft 1 (landRight 1 (0,0)) anymore because when we apply landRight 1 to (0,0) , we don't get a Pole , but a Maybe Pole . landLeft 1 takes a Pole and not a Maybe Pole . [emphasis mine]

+0

ありがとうございました@ゼータ役立ちます。あなたは、誤りのあるコードが正当な価値を与えていると言ったところで、その本に誤字が入っていると言っていますか? – hawkeye

+0

@ hawkeye私は、この章は完全に順番に読む必要があると言っています。スニペットだけを読むと、コードが壊れてしまう可能性があります。 'maybe'を使用していて、 '( - :)'には不適当で、 'Maybe 'を使用しないので、'( - :) 'に適しています。両方の亜種が同じ名前を共有するのは残念です。 – Zeta

関連する問題