0

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!

o1xhack
  • 87
  • 9
  • I don't think `tail(xs)` does what you think it does. – user253751 Oct 03 '16 at 03:28
  • @immibis as I expected it should return the list without the first tuple, so you mean this will not work in a list with tuple?? And what tail give in this code? – o1xhack Oct 03 '16 at 03:34
  • 1
    If I'm not mistaken, `tail(xs)` is the same as `tail (xs)`, so in this context `find d tail(xs)` is the same as `find d tail xs` which "passes three arguments" to `find`. – user253751 Oct 03 '16 at 03:39
  • You probably can't / don't want to change the exercise requirement, but note that returning `'n'` as the error value for "not found" is quite unidiomatic in Haskell. This is because if we get `'n'` back we don't know whether it was found and it was `'n'` or it was not found. A more standard approach would be to return a `Maybe Char` instead of a plain `Char`. – chi Oct 03 '16 at 11:02
  • @chi what do you mean a maybr char? – o1xhack Oct 03 '16 at 17:21

1 Answers1

3

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
Kamel
  • 1,856
  • 1
  • 15
  • 25