Filtering Nothing and unpack Just

前端 未结 2 912
长发绾君心
长发绾君心 2021-01-17 18:56

I\'m having trouble with this program.

filterJust :: [Maybe a] -> [a]

filterJust [] = []
filterJust x = map fromJust (filter (isJust) x)
<
相关标签:
2条回答
  • 2021-01-17 19:29
    • /= can only be used on values of a type that implements Eq ((/=) :: (Eq a) -> a -> a -> Bool).
    • Maybe a supports Eq only if a does (there's an instance (Eq a) => Eq (Maybe a)).
    • Your type signature says that filterJust works for all types a, even those that don't implement Eq: [Maybe a] -> [a]

    Therefore filterJust can't use /=.

    0 讨论(0)
  • 2021-01-17 19:30

    You don't need to write filterJust function. It is already in base and it is called catMaybes: http://hackage.haskell.org/package/base-4.9.0.0/docs/Data-Maybe.html#v:catMaybes

    Also, you can see better way to define this function:

    catMaybes :: [Maybe a] -> [a]
    catMaybes ls = [x | Just x <- ls]
    

    So all you need to do is just add import Data.Maybe (catMaybes) into your module.

    Here this function is using the "MonadFail sugar" design pattern for lists. You can read more about it and other patterns in the following blog post:

    • https://kowainik.github.io/posts/haskell-mini-patterns#monadfail-sugar
    0 讨论(0)
提交回复
热议问题