Haskell: Do we have short cut for mapCons
I mean write such a funct开发者_高级运维ion:
mapCons x [] = [[x]]
mapCons x ys = map (x:) ys
so that:
*> mapCons 'a' []
["a"]
*> mapCons 'a' ["cat", "dog"]
["acat","adog"]
Do we have short-cut or pre-defined functions for mapCons? I tried Hoogle a->[[a]]->[[a]], but didn't find ideal one.
Thanks a lot.
No, and I note that map (x:)
is 8 characters long while typing mapCons x
is 9 characters. For such specific operations (i.e. non-generic operations) the cost and difficulty of finding or remembering them far out weighs the benefits of having them. Imagine if the prelude or base libraries defined 100,000 functions - shudder!
If you import Control.Applicative
you can do things like this:
GOA Control.Applicative> (:) 'a' <$> ["cat", "dog"]
["acat","adog"]
GOA Control.Applicative> (:) <$> [0] <*> [[1,2,3], [7,8,9]]
[[0,1,2,3],[0,7,8,9]]
GOA Control.Applicative> liftA2 (:) "a" ["cat", "dog"]
["acat","adog"]
I know this doesn't satisfy the a->[[a]]->[[a]]
signature you posted, but your question is a bit unclear as to what you are trying to do so I thought this still might help.
You can easily replace mapCons by a simple list comprehension:
mapCons x ys = [x:y | y<-ys]
Like the other solutions, it returns []
if fed with empty ys
, not [[x]]
as your definition.
If we disregard the empty-list case, which, as FUZxxl noticed, does not make much sense, you may notice that:
mapCons = map . (:)
Which, when read out loud, yields something tautological like "mapCons is equal to map composed with cons".
Does not seem useful to me.
精彩评论