如何在 Haskell 中使用 Maybe 对象递归迭代列表

Mar*_*And 4 recursion haskell list option-type

我正在尝试创建一个函数,该函数接受对象justifyList列表( ) 并返回所有类型对象的列表,并丢弃参数列表中的任何元素。Maybe[Maybe a]JustNothing

我现在的解决方案是

justifyList :: [Maybe a] -> [a]
justifyList [] = []
justifyList (x:xs) 
    | (isNothing x) = justifyList xs
    | otherwise = x : justifyList xs
Run Code Online (Sandbox Code Playgroud)

我尝试递归地迭代参数列表,并将当前元素递归地放入x返回的 list 中[a](如果它是Just类型的话)。

但是,在解释时会生成类型不匹配错误

无法将类型 a 与 Maybe a 匹配

因此我的问题是;如何递归地遍历对象列表Maybe?如果这个解决方案足够了,我如何转换xsMaybe类型?

Wil*_*sem 10

这样的函数已经存在于Data.Maybe模块中并被命名为catMaybes :: [Maybe a] -> [a]

您可以通过递归来实现这一点,但使用列表理解来实现这一点可能会更优雅,因为这允许我们同时有效地进行模式匹配和解包,因此:

justifyList :: [Maybe a] -> [a]
justifyList xs = [ x | Just x <- xs ]
Run Code Online (Sandbox Code Playgroud)

仅对于满足Just x模式的项目,它才会生成一个项目,因此Just x <- xs也会执行过滤。


Fyo*_*kin 7

Maybes上的模式匹配

justifyList :: [Maybe a] -> [a]
justifyList [] = []
justifyList (Nothing:xs) = justifyList xs
justifyList (Just x:xs) = x : justifyList xs
Run Code Online (Sandbox Code Playgroud)