o1xhack o1xhack - 1 year ago 142
Python Question

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

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

I got a tuple list here:


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!

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download