Re[Haskell-cafe] cursive to foldr

Ezra Lalonde ezra.lalonde at gmail.com
Tue Nov 17 18:31:19 EST 2009


Using the same basic structure you did, and foldr, I think below is the
simplest method:

====================
import Data.Maybe

searchList :: (a -> Bool) -> [a] -> Maybe [a]
searchList p xs = foldr (\x acc -> if p x then Just (x: fromMaybe [] acc)
else acc) Nothing xs
====================

ghci> searchList (=='o') "A quick brown fox"
Just "oo"
ghci> searchList (==' ') "A quick brown fox"
Just "   "
ghci> searchList (=='z') "A quick brown fox"
Nothing


>From maybe gets rid of the Maybe, so that our recursive call works:
ghci> fromMaybe [] (Just [1..3])
[1,2,3]

That's why we got the error below when we tried without fromMaybe; on
subsequent applications of foldr, the type would have to change.
====================
<interactive>:1:51:
    Couldn't match expected type `[a]'
           against inferred type `Maybe [a]'
    In the expression: if p x then Just (x : acc) else acc
    In the first argument of `foldr', namely
        `(\ x acc -> if p x then Just (x : acc) else acc)'
    In the expression:
        foldr (\ x acc -> if p x then Just (x : acc) else acc) Nothing xs
====================

I have a feeling that using fromMaybe is not the best way, but it gets the
job done for now.

On that note; if somebody with some more experience would chime in, that'd
be awesome. ;)

Ezra


dima.neg wrote:
> 
> How can I do this using foldr?
> 
> searchList p [] = Nothing
> searchList p (x:xs)
> 		| p x = Just (x:filter p xs)
> 		| otherwise = searchList p xs
> 
> 
> I try this: 
> searchList p xs = foldr (\x acc -> if p x then Just (x:acc) else acc)
> Nothing xs
> but don't work.
> 
> Thanks
> 

-- 
View this message in context: http://old.nabble.com/Recursive-to-foldr-tp26368900p26399795.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.



More information about the Haskell-Cafe mailing list