Haskell: Is there an idiomatic way to insert every item in a list into its own list?

筅森魡賤 提交于 2019-11-27 07:47:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!