简体   繁体   English

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

[英]Haskell: list of strings to list of tuples

I have list of strings like: 我有类似的字符串列表:

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

and I would like to get list of tuples like: 我想得到像这样的元组列表:

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

Please help. 请帮忙。 Thanks 谢谢

Edit: 编辑:

I tried something like: 我尝试了类似的东西:

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

which would maybe give me list like: 这可能会给我像这样的列表:

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

but I dont know how to trasnform it to tuples. 但我不知道如何将其转换为元组。

AA,BB,CC should be strings. AA,BB,CC应该是字符串。

Also I would like to if in the list will be something like: 我也想在列表中显示如下内容:

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

transform to 转换为

[(1,"AA",3),(4,6),(7,"CC",9)]
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

A bit of explanation: splitOn splits a String on a given substring, eg 一点解释: splitOn在给定的子String上拆分字符串,例如

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

Next read transforms a String into a different type, which can either be written read "1" :: Int or ghc can infer it by the type signature for you (see read c ). 下次read会将String转换为其他类型,可以将其写入read "1" :: Int或ghc可以通过类型签名为您推断出它(请参阅read c )。

The next line is a "catch all line" that caches all other patterns than [a,b,c] , indicated by _ and results in a runtime error ( undefined ). 下一行是“捕获所有行”,它缓存除_以外的[a,b,c]以外的所有其他模式[a,b,c]_指示),并导致运行时错误( undefined )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM