将字符串列表拆分为字符串列表列表

Split list of strings into list of lists of strings

我有一个字符串列表。我想拆分 space 上的每个字符串,例如使用 words,生成字符串列表的列表。不幸的是,我不能使用 map words myList,因为 map 需要 [a] -> [b],而我想要 [a] -> [[b]]。我该怎么做?

我想到的另一个选项是一个递归函数,我从我的原始列表中分离出 head 字符串,words 然后在那里分析结果,但我试图使用预先存在的函数和一行来完成。

我不确定我是否理解,你可以使用mapwords来产生这样的结果:

GHCi, version 7.10.1: http://www.haskell.org/ghc/  :? for help
Prelude> let { splitWords [] = []; splitWords ws = map words ws }
Prelude> splitWords []
[]
Prelude> splitWords ["first sentence", "second sentence"]
[["first","sentence"],["second","sentence"]]
Prelude> 

我认为这里要指出的重要一点是,map 期望 (a -> b) -> [a] -> [b] 并不意味着 b 必须与 a 是同一类型。这里 a 是一个字符串,b 是一个 [String]

'map' 的类型签名是

map :: (a -> b) -> [a] -> [b]

'words' 的类型签名是

words :: String -> [String]

因此,'map words'的类型签名是

map words :: [String] -> [[String]]

嘿,这正是你想要的!我们来试试吧。

map words ["hello world","stack exchange"]

输出:

[["hello","world"],["stack","exchange"]]