I am trying to understand how to write functions using tail recursion in Haskell. In my example below, the function takes in a list and outputs the maximum value in the list. My intention is to use the c variable to store the current max. I was wondering if someone can explain how using tail recursion would work for this instance?
myMax [] c = error "max of empty list"
myMax [x] c = x
myMax (x:xs) c =
if x > myMax xs then c = x
else myMax xs c
--currently getting a parse error
There are a couple things to think about here. First You don’t want the user to have to enter some beginning value, so we want a function that takes only a list as its parameter. Since you want a tail recursive implementation we do need a function that takes a second parameter though, so we’ll create an inner function named
gowhich takes the current max and the remaining list.Note that we never changed the value of any variable here. We update the current max value
by passing it as a parameter to the next step in the function. This is critical to understand in Haskell because mutating variables is not allowed.