[Haskell-beginners] Abstracting Data.List
Alexander V Vershilov
alexander.vershilov at gmail.com
Sat Jun 1 07:25:06 CEST 2013
I need to add that it's perfectly valid to define all operation in terms of
Folds and so it's possible to define take, head, and such functions for all
Foldable instances as they have a path to fold over them:
the key idea is to store a state while folding over a structure:
headF :: (Foldable x) => x a -> a
headF = snd . F.foldl (\(s,v) n -> if s then (s,v) else (True,n)) (False,
error "empty")
takeF :: (Foldable x) => Int -> x a -> [a]
takeF c = reverse . snd . F.foldl (\(i,v) n -> if i < c then (i+1,n:v) else
(i,v)) (0,[])
In domain of a lazy languages we will even stop evaluation as soon as we
will get result without additional steps.
On 31 May 2013 18:31, Brandon Allbery <allbery.b at gmail.com> wrote:
> On Fri, May 31, 2013 at 6:16 AM, mukesh tiwari <
> mukeshtiwari.iiitm at gmail.com> wrote:
>
>> Data.List can be abstracted using Foldable and Traversable but
>> unfortunately I could not find the functions corresponding to head, take.
>>
>
> Those are, again, more general than you want. What is the `head` of a
> HashMap? (Consider that an implementation may choose to randomize the hash
> function to avoid hash collision attacks.) Foldable and Traversable express
> the concept of a collection which has no meaningful concept of an element's
> relative position within the collection. ListLike adds the concept of
> position, thereby admitting an indexing operation (and, by extension,
> `head` which is index 0).
>
> --
> brandon s allbery kf8nh sine nomine
> associates
> allbery.b at gmail.com
> ballbery at sinenomine.net
> unix, openafs, kerberos, infrastructure, xmonad
> http://sinenomine.net
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
--
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130601/9500b75d/attachment.htm>
More information about the Beginners
mailing list