简体   繁体   中英

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.

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

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 ).

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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