Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Nothing and unpack Just

Tags:

haskell

I'm having trouble with this program.

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

filterJust [] = []
filterJust x = map fromJust (filter (isJust) x)

but ghci keeps reporting this

but ghci keeps reporting this

EDIT:

I don't want to use any additional module so i made this:

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

filterJust x = map unpack (filter (Nothing /=) x)

unpack (Just a) = a

and i get this message

and i get this message

and i dont understand why. I should be able to use Eq functions without importing anthing right?

like image 852
Tibor Bujdoš Avatar asked Oct 30 '16 09:10

Tibor Bujdoš


2 Answers

You don't need to write filterJust function. It is already in base and it is called 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
like image 170
Shersh Avatar answered Nov 12 '22 03:11

Shersh


  • /= 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 /=.

like image 3
melpomene Avatar answered Nov 12 '22 04:11

melpomene