简体   繁体   中英

How to parse ints out of string in Haskell

I'm trying to parse strings of the format:

(x,y) (r,g,b)

My file contains this kind of string on each line. I already extracted the lines, now i wanna extract its values, but i couldn't find something satisfying. I wanted to do something like :

case str of
['(', x, ',', y, ')', ' ', '(', r, ',', g, ',', b, ')'] -> The rest

I know it doesn't work, I'm new to Haskell so i keep encountering errors i don't understand. How can i make it ?

EDIT : I have created this before, but i don't know how to really use it once the variable has been created :

data Points = Point Coords Colors
data Colors = Color Float Float Float
data Coords = Coord Int Int

Numbers are not limited to one digit, r, g and b range from 0 to 255.

An easy hack for this particular task:

data Pix = Pix (Int,Int) (Int,Int,Int)
 deriving (Read, Show)

parsePix :: ReadS Pix
parsePix s = reads $ "Pix "++s
*Main> parsePix "(1,2) (3,4,5)"
[(Pix (1,2) (3,4,5),"")]

In general, you should look into proper parser-combinator libraries though, I recommend megaparsec .

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