Haskell:元组列表的字符串列表

时间:2016-04-08 19:44:06

标签: haskell

我有以下字符串列表:

["1,AA,3","4,BB,6","7,CC,9"]

我希望得到像元组列表:

[(1,AA,3),(4,BB,6),(7,CC,9)]

请帮忙。感谢

编辑:

我尝试过类似的事情:

tuples (x:xs) = do
  foo ++ splitOn "," x
  tuples xs
  return foo

这可能会给我列表如下:

"1,AA,3,4,BB,6,7,CC,9"

但我不知道如何将它转换为元组。

AA,BB,CC应为字符串。

此外,我想在列表中的内容如下:

["1,AA,3","4,,6","7,CC,9"]

转换为

[(1,"AA",3),(4,6),(7,"CC",9)]

1 个答案:

答案 0 :(得分:5)

import Data.List.Split -- https://hackage.haskell.org/package/split

arrayToThreeTuple :: [String] -> [(Int,String,Int)]
arrayToThreeTuple = map (toThreeTuple.splitOn ",")
    where
      toThreeTuple :: [String] -> (Int, String, Int)
      toThreeTuple [a, b, c] = (read a :: Int, b, read c)
      toThreeTuple _ = undefined

一点解释:splitOn在给定子字符串上拆分String,例如

GHCI List.Split> splitOn "," "1,AA,3"
["1","AA","3"]

下一个readString转换为另一种类型,可以写成read "1" :: Int或ghc可以为您推断类型签名(请参阅read c

下一行是"赶上所有行"缓存[a,b,c]以外的所有其他模式,由_表示,并导致运行时错误(undefined)。