问题
I've been using ((:[]) <$> xs)
but if there is a more clear way I would love to use it.
edit: so many good answers guys! I don't think I can accept one because they are all good.
回答1:
I believe map return
or map pure
are good enough.
回答2:
Maybe this?
map (\x -> [x]) xs
Yours can work on any functor I think so this would be more idomatic for just lists.
回答3:
The split package provides a (Data.List.Split.)chunksOf function whose name is, IMO, more meaningful than the various map solutions (even if they are more idiomatic.)
回答4:
You can also use a list comprehension:
[ [x] | x <- theList]
Maybe overkill for such a simple example, but depending on your context, maybe you can merge this step with some further processing of the singleton lists:
[f [x] + 13 | x <- theList]
回答5:
Tongue-in-cheek version:
import Data.List
groupBy (const . const False) xs
回答6:
Using do
notation:
do { x <- xs; return [x] }
来源:https://stackoverflow.com/questions/17495179/haskell-is-there-an-idiomatic-way-to-insert-every-item-in-a-list-into-its-own-l