haskell: recursive function that return the char in a tuple list with certain condition(compare)

纵然是瞬间 提交于 2020-01-07 04:03:27

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/39823833/haskell-recursive-function-that-return-the-char-in-a-tuple-list-with-certain-co

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!