Home > Enterprise >  Can anyone help me solve this problem with recursion in lists?
Can anyone help me solve this problem with recursion in lists?

Time:10-13

I'm new to Haskell and not the greatest at math. I've been given an assignment in which one of the points ask us to: "Make a function that, given a list with values, returns the position of the first value greater than the one sent as a parameter. In case it's not found, return -1. You must use recursion"

The solution I came up with is the following:

posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA [] a = (-1) 
posicionPrecioMayorA (x:xs) a
    | x > a = 0
    | otherwise = 1   posicionPrecioMayorA xs a

But it has a main problem, in case it doesn't find a number greater than the parameter, the otherwise sentence will keep on counting until [] and then add (-1) to it in the traceback.

Example:

posicionPrecioMayorA [10,15,30] 100 => 2

Hopefully someone can help me fix it. Thank you!

CodePudding user response:

You can create a helper function and keep track of the position you are at while recusring.

posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA xs a = go xs a 0 where
  go [] _ _ = -1
  go (x:xs) a c
    | x > a = c
    | otherwise = go xs a (c 1)

CodePudding user response:

You say your problem is that, if it didn't find the searched-for element, then it keeps adding 1 to the counter anyway. Well, that sounds like a perfectly good description of the problem: you add unconditionally, where you wish you added conditionally. So, just write a condition into your program, and don't add 1 if the result is -1:

posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA [] a = (-1)
posicionPrecioMayorA (x:xs) a
    | x > a = 0
    | otherwise = case posicionPrecioMayorA xs a of
                    -1 -> -1
                    index -> 1   index
  • Related