Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use 'isJust' in the lambda function in `foldr`?

I am currently writing an interpreter in haskell for a primitive programming language. I am trying to see if the current program being analysed is correctly Typed before interpreting. Basically what I end up with is a list called maybeList that holds maps of the initialised variables if they are correct, or Nothings if they don't, like this:

[Maybe [(k,v)]]

I am trying to fold over this list with this function

foldr (\x y -> (isJust x) && (isJust y)) True maybeList

From what I understand about Haskell and the foldr function, this should work. However, it gives me the error:

Couldn't match expected type ‘Bool’ with actual type ‘Maybe a0’ 
In the expression:

 foldr (\ x y -> (isJust x) && (isJust y)) True maybeList

What I'm asking is why doesn't the compiler know that the isJust function returns a boolean, it keeps treating it as a Maybe a0 type?

P.S. I understand that a simple elem Nothing maybeList will work in place of this. But I would like to understand why this doesn't work

like image 836
Devon Gregory Avatar asked Jun 11 '21 10:06

Devon Gregory


1 Answers

The reducing function for foldr takes as second argument something of the same type as the initial element:

foldr (\x y -> (isJust x) && (isJust y)) True maybeList
--        \_______________________________/    
--                         |
--          these two must be the same type

So y is of type Bool but you are considering it of type Maybe a.

Therefore, foldr (\x y -> (isJust x) && y) True maybeList is the right solution.

like image 165
lsmor Avatar answered Nov 15 '22 06:11

lsmor