algorithm - Haskell Recursion - finding largest difference between numbers in list -


here's problem @ hand: need find largest difference between adjacent numbers in list using recursion. take following list example: [1,2,5,6,7,9]. largest difference between 2 adjacent numbers 3 (between 2 , 5).

i know recursion may not best solution, i'm trying improve ability use recursion in haskell.

here's current code have:

largestdiff (x:y:xs) = if (length (y:xs) > 1) max((x-y), largestdiff (y:xs)) else 0 

basically - list keep getting shorter until reaches 1 (i.e. no more numbers can compared, returns 0). 0 passes call stack, max function used implement 'king of hill' type algorithm. - @ end of call stack, largest number should returned.

trouble is, i'm getting error in code can't work around:

occurs check: cannot construct infinite type:   t1 = (t0, t1) -> (t0, t1) in return type of call of `largestdiff' probable cause: `largestdiff' applied few arguments in expression: largestdiff (y : xs) in first argument of `max', namely   `((x - y), largestdiff (y : xs))' 

anyone have words of wisdom share?

thanks time!

edit: time - ended independently discovering simpler way after trial , error.

largestdiff [] = error "list small" largestdiff [x] = error "list small" largestdiff [x,y] = abs(x-y) largestdiff (x:y:xs) = max(abs(x-y)) (largestdiff (y:xs)) 

thanks again, all!

so reason why code throwing error because

max((x-y), largestdiff (y:xs)) 

in haskell, not use parentheses around parameters , separate them commas, correct syntax is

max (x - y) (largestdiff (y:xs)) 

the syntax used getting parsed as

max ((x - y), largestdiff (y:xs)) 

which looks you're passing tuple max!

however, not solve problem. got 0 back. instead, recommend breaking problem 2 functions. want calculate maximum of difference, first write function calculate differences , function calculate maximum of those:

diffs :: num => [a] -> [a] diffs [] = []                            -- no elements case diffs [x] = []                           -- 1 element case diffs (x:y:xs) = y - x : diffs (y:xs)    -- 2 or more elements case  largestdiff :: (ord a, num a) => [a] -> largestdiff xs = maximum $ map abs $ diffs xs 

notice how i've pulled recursion out simplest possible case. didn't need calculate maximum traversed list; it's possible, more complex. since haskell has handy built-in function calculating maximum of list us, can leverage that. our recursive function clean , simple, , combined maximum implement desired largestdiff. fyi, diffs function compute derivative of list of numbers, can useful function data processing.

edit: needed ord constraint on largestdiff , added in map abs before calculating maximum.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -