获取[[String]] Haskell的输入

时间:2017-09-17 16:05:34

标签: string list haskell input

我希望将输入作为列表列表。 每行文本必须是字符串列表,全文将是列表列表。我怎么能这样做? 我把它作为主要的:

main :: IO ()
main = interact (lines >>> foo >>> unlines)

所以如果这是输入:

These are random
Words of text
example example example

结果应该是这样的:

[[These, are, random], [Words, of, text],[example, example, example]]

1 个答案:

答案 0 :(得分:1)

Haskell有一个函数words :: String -> [String]。例如:

Prelude> words "These are random"
["These","are","random"]

现在我们可以使用map :: (a -> b) -> [a] -> [b]

为行列表执行此操作
Prelude> map words ["These are random","Words of text","example example example"]
[["These","are","random"],["Words","of","text"],["example","example","example"]]

您可以将其与lines结合使用,首先提取字符串的行:

Prelude> (map words . lines) "These are random\nWords of text\nexample example example"
[["These","are","random"],["Words","of","text"],["example","example","example"]]

因此,如果foo的类型为foo :: [[String]] -> [[String]],则可以使用:

main = interact (unlines . map unwords . foo . map words . lines)