作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 Haskell 的新手,有这段代码:
import Control.Monad
data NestedList a = Elem a | List [NestedList a] deriving (Show)
instance Monad NestedList where
return a = List [Elem a]
(List (Elem a: xs)) >>= f = let a' = f a in a' `joinLists` xs
func :: a -> NestedList a
func a = List ([Elem a] ++ [Elem a])
joinLists :: NestedList a -> [NestedList a] -> NestedList a
joinLists (List a) b = List (a ++ b)
main = do let a = List [Elem 1, Elem 2] >>= func
print a
我想做的是获取一个包含元素的列表,复制列表的第一个元素并向该列表添加一个尾部。因此 List [Elem 1, Elem 2] 将等于 List [Elem 1, Elem 1, Elem 2]。我知道这不是使用 Monad 的好例子,但这是为了学习。
我收到这样的错误:
Couldn't match type 'a' with 'b'
'a' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
'b' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
Expected type: [NestedList b]
Actual type: [NestedList a]
In the second argument of 'joinLists', namely 'xs'
我知道错误是它需要一个不同类型的 NestedList 变量。这里有什么问题吗?
最佳答案
I know that's not a good example of using Monads, but that's for the sake of learning.
具体来说,您的 >>=
实现不够通用。您给出的内容类型为:
List a -> (a -> List a) -> List a
但 haskell 坚持
List a -> (a -> List b) -> List b
对我来说,似乎没有什么好方法可以在 monad 中实现您想要的目标。
更深层次的原因是你想要修改“容器”的结构,而不是以容器特定的方式对“元素”做一些事情。
关于 haskell 错误: Couldn't match type 'a' with 'b' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425853/
我是一名优秀的程序员,十分优秀!