0

我是函数式编程和 CLEAN 的新手。我有一些功能,但我有一个错误,我不知道为什么。(我用 Haskell 标记了它,因为它与 CLEAN 非常相似。)

我的模块:

module Prac

combine :: (Maybe a) (Maybe [a]) -> Maybe [a]
combine Nothing _ = Nothing
combine _ Nothing = Nothing
combine (Just d) (Just [x:xs]) = Just [d, x:xs]

sequence :: [Maybe a] -> Maybe [a]
sequence [Just x:xs] =  combine  (Just x)  Just[xs]

它在序列定义中失败:

 Type error [Prac.icl,32,sequence]: near combine : cannot unify types:
 [v8] -> Maybe [v4]
 Maybe [v5]

非常感谢!!

4

1 回答 1

5

这将在 Haskell 中工作:

combine :: Maybe a -> Maybe [a] -> Maybe [a]
combine Nothing _ = Nothing
combine _ Nothing = Nothing
combine (Just d) (Just xs) = Just (d:xs)

sequence :: [Maybe a] -> Maybe [a]
sequence [] = Just []
sequence (a:xs) =  combine  a (sequence xs)

但我不确定它是否符合您的要求:

λ> sequence [Just 1, Just 3, Just 4]
Just [1,3,4]

λ> sequence [Just 1, Nothing, Just 4]
Nothing

λ> sequence []
Just []

好的,我找到了一个翻译方案- 但没有保证,因为我现在没有办法对其进行正确测试

sequence :: [Maybe a] -> Maybe [a]
sequence [] = Just []
sequence [x:xs] =  combine x (sequence xs)

虽然不确定空列表和签名 - 抱歉

无论如何,如果您可以重用将给定列表的头部与尾部的递归计算序列相结合的想法,那么您应该没问题

这适用于我使用干净

所以我只是下载了IDE,做了一个项目,添加了一个模块:

module seq

:: MayBe a = Just a | Nothing

Start = sequence [Just 3, Just 4, Just 5]

combine Nothing _ = Nothing
combine _ Nothing = Nothing
combine (Just d) (Just xs) = Just [d:xs]

sequence [] = Just []
sequence [x:xs] =  combine x (sequence xs)

编译了这个,更新了项目并运行了它——这里可行

于 2014-10-14T08:53:25.850 回答