简体   繁体   English

如何在Haskell中解析字符串中的整数

[英]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. 我知道它不起作用,我是Haskell的新手,所以我一直遇到我不明白的错误。 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. 数字不限于一位,r,g和b的范围是0到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 . 通常,尽管我建议使用megaparsec ,但您应该研究适当的解析器-组合器库。

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

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