简体   繁体   English

在Haskell中将字符串转换为具有设置布局的列表

[英]Converting a string of characters into a list with a set layout in Haskell

I've got the following function to enlarge, it takes a string such as "5a" and it outputs in a list, ie [('a',5)] . 我有以下函数可以放大,它需要一个字符串,例如“ 5a”,并在列表中输出, [('a',5)] How could I change it so that it allows the input of more than just 1 pair, so if something like "5a5b" was input, the output would be [('a',5),('b',5)] ? 我如何更改它以使其允许多于一对的输入,所以如果输入类似“ 5a5b”的内容,则输出将为[('a',5),('b',5)]吗?

The current code that I have for this is here: 我为此的当前代码在这里:

enlarge :: String -> [(Char,Int)]
enlarge [] = []
enlarge xs = [(a,b) | (b,a:_) <- reads xs]

The code above works and it will work for just one pair, ie if "5a" is input, it will output [('a',5)] . 上面的代码有效,并且仅适用于一对, 即,如果输入“ 5a”,则将输出[('a',5)] However, I'd like to change it so that it will allow more than just one pair, ie if "5a3b" is input, the output should be [('a',5),('b',3)] . 但是,我想对其进行更改,以便允许仅一对输入,即,如果输入“ 5a3b”,则输出应为[('a',5),('b',3)] Currently, it only takes into consideration the first 2 parts of the string. 当前,它仅考虑字符串的前两个部分。

My attempt at doing this is here: 我的尝试是在这里:

enlarge xs = [((a,b),ts) | ((b,a),ts) <- reads xs, reads ts]

And what i'm trying to do here, is first get the pair for the first two characters, and then read any more characters and then do the same to those. 我在这里尝试做的是,首先获取前两个字符对,然后读取更多字符,然后对这些字符做同样的事情。

I wrote a recursive code for your request. 我为您的请求编写了一个递归代码。

enlarge :: String -> [(Char,Int)]
enlarge [] = []
enlarge (x:y:ls) = [(y,digitToInt x)] ++ enlarge ls

Here, the code assumes that the input length is even. 在此,代码假定输入长度为偶数。 And used digitToInt to convert the Char to Int. 并使用digitToInt将Char转换为Int。

We need more input-output examples. 我们需要更多的输入输出示例。 For example what should happen to "12z" ? 例如, "12z"应如何处理? Also it is not really clear what reads means. 另外,还不清楚reads是什么意思。 But I think you want this 但是我想你想要这个

[(c, read i :: Int) | [i, c] <- chunksOf 2 xs]

Don't forget to import chunksOf , which can be found in Data.List.Split . 不要忘记导入chunksOf ,可以在Data.List.Split中找到

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

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