简体   繁体   English

Haskell int list to String

[英]Haskell int list to String

I would like to know if there is a simple way to turn [5,2,10] into "52a" . 我想知道是否有一种简单的方法可以将[5,2,10]变成"52a" Where its not just to this case, I want to associate any number >9 with the corresponding letter. 不仅仅是在这种情况下,我想将任何数字> 9与相应的字母相关联。

Thanks in advance. 提前致谢。

You want to do something to each element of a list in order to get a new list. 您希望对列表的每个元素执行某些操作以获取新列表。 In other words, you want to apply a function (that you will have to define yourself) to each element. 换句话说,您希望将一个函数(您必须自己定义)应用于每个元素。 This is what the map function from the Prelude is for. 这就是Prelude的地图功能。

To convert between integers and individual characters, you could use the chr and ord functions from the Data.Char module. 要在整数和单个字符之间进行转换,可以使用Data.Char模块中的chr和ord函数。

So, 所以,

map (\i -> if i < 10 then chr (i + ord '0') else chr (i - 10 + ord 'a'))

is a function of type [Int] -> String that does what you want (no error checking included, though). 是[Int] - > String类型的函数,它可以执行您想要的操作(但不包括错误检查)。

Slower but more elegant: 更慢但更优雅:

f = map ((['0'..'9'] ++ ['a'..'z']) !!)

If your numbers are 0-15 use map intToDigit from Data.Char. 如果您的数字是0-15,请使用map intToDigit intToDigit。

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

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