[Haskell-cafe] Is "take" behaving correctly?

Don Stewart dons at galois.com
Tue Sep 11 19:47:30 EDT 2007

>    I suppose I'm thinking of head or tail - e.g. head [] or tail [].
>    I'm trying to write my own version of the find function. I have a few
>    ideas but not quite sure which would be more suitable in the context of
>    FP.
>    Any advice would be gratefully received - e.g. do I use recursion, list
>    comprehension or what?

Well, you want to filter all elements from a list that match a predicate, 
and then return Just the first match, or Nothing?

	find :: (a -> Bool) -> [a] -> Maybe a

Checking the current behaviour:

	> find isSpace "haskell is fun"
	Just ' '

My first go would be something like this: ok, so let's start with 'filter':

	> filter Char.isSpace "haskell is fun"
	"  "

Good, then the natural translation to the Maybe type:

	> listToMaybe . filter isSpace $ "haskell is fun"
	Just ' '

And we're almost done. Just firing up QuickCheck:

	> quickCheck $ \p (xs :: [Int])  -> find p xs == listToMaybe (filter p xs)
	OK, passed 100 tests.

Seems ok.

I hope that gives some insight into the process of deriving Haskell 
implementations by building up a pipeline of pieces.

-- Don

More information about the Haskell-Cafe mailing list