haskell:递归函数,返回具有一定条件的元组列表中的字符(比较) [英] haskell: recursive function that return the char in a tuple list with certain condition(compare)

查看:173
本文介绍了haskell:递归函数,返回具有一定条件的元组列表中的字符(比较)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在这里得到了一个元组列表:

  [(0.5,'!'),(1,'*'),(1.5,'#')] 

我想要做的是输入一个数字n并与列表中每个元组的第一个数字进行比较



假设n = 0.1,当它比较0.5并且发现它小于0.5时,它将返回char'!'



假设n = 0.7,这就是> 0.5并继续比较,发现它< 1,那么它将返回char'*'



,并且比较整个列表并发现d仍然比最后一个大,它将返回char'n'



我一直在用这样的条件工作很多时间,但仍然无法得到这个,这里是我的代码:

  find :: Double  - > [(Double,Char)]  - > Char 
find d [] =''
找到d xs
| d <= Double(xs [0])= xs [0]
| d> Double(xs [0])= find d tail(xs)

请使用递归!

解决方案

元组与Haskell中的数组不同

  find :: Double  - > [(Double,Char)]  - > char 
find d [] =''
找到d(x:xs)
| d <= fst x = snd x
|否则=找到d xs


I'm learning recursive function in haskell that confused with such conditon:

I got a tuple list here:

[(0.5,'!'),(1,'*'),(1.5,'#')]

What I want to do is input a number n and compare with fist number in each tuple of the list

so suppose n=0.1, when it compared 0.5 and find it is smaller than 0.5, it will return char '!'

suppose n=0.7, which is > 0.5 and keep comparing, find that it < 1, then it will return char '*'

and after compare the whole list and find d is still bigger than the last one, it will just return char 'n'

I've been work with such condition lots of time,but still cannot get to this, here is my code:

find :: Double -> [(Double,Char)] -> Char
find d [] = ' '
find d xs
    | d <= Double(xs[0]) = xs[0]
    | d > Double(xs[0]) = find d tail(xs)

please use recursion!

解决方案

tuple is different from array in Haskell

find :: Double -> [(Double,Char)] -> Char
find d [] = ' '
find d (x:xs)
    | d <= fst x = snd x
    | otherwise = find d xs

这篇关于haskell:递归函数,返回具有一定条件的元组列表中的字符(比较)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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