[Haskell-beginners] question about list processing

Martin Vlk martin at vlkk.cz
Thu Nov 12 13:26:03 UTC 2015


Oh, and a little background.

fmap comes from the Functor typeclass, and lists have an instance of
Functor so the empty list case is handled automatically.

Then I used "take 1" to get the head in a safe way, e.g. defaulting to
empty list if the output of fmap is empty.

M.

Martin Vlk:
> How about:
> 
> computeHead f = take 1 . fmap f
> 
> Martin
> 
> Dennis Raddle:
>> What would be an elegant way of writing this
>>
>> computeHead :: (a -> [b]) -> [a] -> [b]
>>
>> Where when [a] is null, it returns a null list, but when [a] contains one
>> or more elements, it applies the given function to the head of a and
>> returns that? Is there some existing typeclass operator that facilitates
>> this?
>>
>> You can write
>>
>> computeHead _ [] = []
>> computeHead f (x:_) = f x
>>
>> But that first line seems suspicious to me... it makes me think about how
>> in the list Monad, an empty list falls through. But I can't quite make it
>> work.
>>
>>
>>
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
> 
> 


More information about the Beginners mailing list