user12174294
user12174294

Reputation:

Need help storing the previous element of a list (Haskell)

I'm currently working on an assignment. I have a function called gamaTipo that converts the values of a tuple into a data type previously defined by my professor. The problem is: in order for gamaTipo to work, it needs to receive some preceding element. gamaTipo is defined like this: gamaTipo :: Peca -> (Int,Int) -> Peca where Peca is the data type defined by my professor.

What I need to do is to create a funcion that takes a list of tuples and converts it into Peca data type. The part that im strugling with is taking the preceding element of the list. i.e : let's say we have a list [(1,2),(3,4)] where the first element of the list (1,2) always corresponds to Dirt Ramp (data type defined by professor). I have to create a function convert :: [(Int,Int)] -> [Peca] where in order to calculate the element (3,4) i need to first translate (1,2) into Peca, and use it as the previous element to translate (3,4)

Here's what I've tried so far:

    updateTuple :: [(Int,Int)] -> [Peca]
    updateTuple [] = []
    updateTuple ((x,y):xs) = let previous = Dirt Ramp
                                in (gamaTipo previous (x,y)): updateTuple xs

Although I get no error messages with this code, the expected output isn't correct. I'm also sorry if it's not easy to understand what I'm asking, English isn't my native tongue and it's hard to express my self. Thank you in advance! :)

Upvotes: 1

Views: 262

Answers (1)

bradrn
bradrn

Reputation: 8467

If I understand correctly, your program needs to have a basic structure something like this:

updateTuple :: [(Int, Int)] -> [Peca]
updateTuple = go initialValue
  where
    go prev (xy:xys) =
        let next = getNextValue prev xy
        in prev : (go next xys)
    go prev [] = prev

Basically, what’s happening here is:

  • updateTuple is defined in terms of a helper function go. (Note that ‘helper function’ isn’t standard terminology, it’s just what I’ve decided to call it).
  • go has an extra argument, which is used to store the previous value.
  • The implementation of go can then make use of the previous value.
  • When go recurses, the recursive call can then pass the newly-calculated value as the new ‘previous value’.

This is a reasonably common pattern in Haskell: if a recursive function requires an extra argument, then a new function (often named go) can be defined which has that extra argument. Then the original function can be defined in terms of go.

Upvotes: 1

Related Questions