0
votes

I wrote a function and it complies, but I'm not sure if it works the way I intend it to or how to call it in the terminal. Essentially, I want to take a string, like ("age",5),("age",6) and make it into a list of tuples [("age1",5)...]. I am trying to write a function separate the commas and either I am just not sure how to call it in the terminal or I did it wrong.

items :: Parser (String,Integer) -> Parser [(String,Integer)]
items p =  do { p <- sepBy strToTup (char ",");
                return p }
1
Use the parameter: items p = sepBy p (char ',')4castle
I want it to be the symbol ",", not the char, but when I try to make the adjustment it doesn't workbarskyn
Please include in your question a minimal reproducible example along with the error message.4castle

1 Answers

1
votes

I'm not sure what you want and I don't know what is Parser.

Starting from such a string:

thestring = "(\"age\",5),(\"age\",6),(\"age\",7)"

I would firstly remove the outer commas with a regular expression method:

import Text.Regex
rgx = mkRegex "\\),\\("
thestring' = subRegex rgx thestring ")("

This gives:

>>> thestring'
"(\"age\",5)(\"age\",6)(\"age\",7)"

Then I would split:

import Data.List.Split
thelist = split (startsWith "(") thestring'

which gives:

>>> thelist
["(\"age\",5)","(\"age\",6)","(\"age\",7)"]

This is what you want, if I correctly understood.

That's probably not the best way. Since all the elements of the final list have form ("age", X) you could extract all numbers (I don't know but it should not be difficult) and then it would be easy to get the final list. Maybe better.

Apologies if this has nothing to do with your question.

Edit

JFF ("just for fun"), another way:

import Data.Char (isDigit)
import Data.List.Split
thestring = "(\"age\",15),(\"age\",6),(\"age\",7)"
ages = (split . dropBlanks . dropDelims . whenElt) (not . isDigit) thestring
map (\age -> "(age," ++ age ++ ")") ages
-- result: ["(age,15)","(age,6)","(age,7)"]

Or rather:

>>> map (\age -> ("age",age)) ages
[("age","15"),("age","6"),("age","7")]

Or if you want integers:

>>> map (\age -> ("age", read age :: Int)) ages
[("age",15),("age",6),("age",7)]

Or if you want age1, age2, ...:

import Data.List.Index
imap (\i age -> ("age" ++ show (i+1), read age :: Int)) ages
-- result: [("age1",15),("age2",6),("age3",7)]