无法理解Haskell的类型系统

Dai*_*air 8 constructor haskell types overloading algebraic-data-types

我目前正在尝试做20次中级Haskell练习.我能够完成前3个练习(但这是因为furry== fmap并且了解你,Haskell已经有了这些实现).我目前卡在那个说:

instance Fluffy (EitherLeft t) where                                        
  furry = error "todo"
Run Code Online (Sandbox Code Playgroud)

我真的不明白该怎么做.在Learn You Haskell中,他们有一个newtype变量Pair,它接受一个元组.然后他们可以进行模式匹配:

  fmap f (Pair (x,y)) = Pair (f x, y)
Run Code Online (Sandbox Code Playgroud)

我想也许你可以在我的情况下做类似的事情:

  furry f (EitherLeft (Either a b)) = EitherLeft (Either (f a) b)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:

Not in scope: data constructor `Either'
Run Code Online (Sandbox Code Playgroud)

我想也许我愿意,import Data.Either因为可能有一些他没有的重要东西.但那没关系.

我也尝试让这个工作:

  furry f (EitherLeft a b) = error "todo"
Run Code Online (Sandbox Code Playgroud)

但这也不起作用:

Constructor `EitherLeft' should have 1 argument, but has been given 2
Run Code Online (Sandbox Code Playgroud)

我无法让这个工作:

  furry f (Right x) = (Right f x)
  furry f (Left x) = Left x
Run Code Online (Sandbox Code Playgroud)

这给出了错误:

Couldn't match expected type `EitherLeft t a'
            with actual type `Either t0 t1'
Run Code Online (Sandbox Code Playgroud)

我只能得到:

  furry f (EitherLeft t) = error "todo"
Run Code Online (Sandbox Code Playgroud)

上班.但我不知道该怎么做t.

我不一定想要答案.我只需要提示一下该做什么,因为我正在阅读,我可以解释一下,理解这些例子,但我不能真正理解我自己编写这些东西.

谢谢Dan,这就是我提出的解决方案:

instance Fluffy (EitherLeft t) where                     
  furry f (EitherLeft (Left x)) = EitherLeft $ Left  (f x)                   
  furry f (EitherLeft (Right x)) = EitherLeft $ Right x
Run Code Online (Sandbox Code Playgroud)

Dan*_*tey 13

您遇到的问题是Either数据类型没有名为Either的数据构造函数,基本上Either类型看起来像这样

data Either a b = Left a
                | Right b
Run Code Online (Sandbox Code Playgroud)

所以一个值可以有类型Either a b,但没有像这样的值Either "one" 1或类似的东西,而是Left "one",或者Right 1.

因此,在EitherLeft类似情况下,其值看起来像EitherLeft (Left a)或者EitherLeft (Right b),并且需要进行模式匹配.