I have a string something like this "3,4\r\n", and I want to convert them into a tuple i.e (3,4).
How can we achieve this in SML ?
The reason why I’m getting a string value is because I’m reading a file which returns strings like that.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need a simple parser to achieve that. An appropriate function to parse integers is already available in the library as
Int.scan(along with friends for other types), but you have to write the rest yourself. For example:And then, to parse all lines:
To use it, for example:
As you can see, the code is a bit repetitive. To get rid of all the matching of option types you could write a few basic parser combinators:
There are a lot more cool abstractions you can build along these lines, especially when defining your own infix operators. But I’ll leave it at that.
You might also want to handle white space between tokens. The
StringCvt.skipWSreader is readily available in the lib for that, just insert it in the right places.