Haskell int list to String [英] Haskell int list to String

查看:137
本文介绍了Haskell int list to String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有简单的方法将 [5,2,10] 变成52a
如果不是这种情况,我想将任何数字> 9与相应的字母关联。



在此先感谢您。

解决方案

您想对列表中的每个元素执行某些操作以获取新列表。换句话说,你想要为每个元素应用一个函数(你必须定义自己)。这是Prelude的映射函数的作用。



要在整数和单个字符之间进行转换,可以使用Data.Char模块中的chr和ord函数。

因此,

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

是一个类型为[Int] - > String的函数,它可以完成你想要的操作(不包括错误检查)。


I would like to know if there is a simple way to turn [5,2,10] into "52a". Where its not just to this case, I want to associate any number >9 with the corresponding letter.

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.

To convert between integers and individual characters, you could use the chr and ord functions from the Data.Char module.

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).

这篇关于Haskell int list to String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆