1
votes

There is probably a simple answer to this, but I am new to Haskell. I am trying to iterate through a function parameter and use each list element to call another function. I have a function that performs a move given the game board, the move, and the player number and returns the new game board. Its function header looks like this:

play :: [[Char]] -> Char -> Char -> [[Char]]
play gameBoard moveDirection playerSymbol = ...

I am trying to call it from a driver function that has the parameters of the initial game board and a list of moves to be performed on the game board. Is there a way to call the play function for each element in the move list such that the gameExample function below return the game board after every move has been made?

moveDirections = "udlrudlr"
gameExample :: [[Char]] -> [Char] -> [[Char]]
gameExample gameBoard (moveDirection : moveDirections) = 
    play gameBoard moveDirection 'p'

Please let me know if you require any clarifications.

1
Calling a function for each element of the list, feeding each call's output to the input of the next, is known as a fold. See foldl and foldr - luqui

1 Answers

2
votes

You can do it with explicit recursion:

gameExample gameBoard [] = gameBoard
gameExample gameBoard (moveDirection : moveDirections) =
    gameExample (play gameBoard moveDirection 'p') moveDirections

Or you can use the foldl function to do that for you:

gameExample = foldl (\gameBoard moveDirection -> play gameBoard moveDirection 'p')

There's also Data.Foldable.foldl', which is usually better for performance than foldl is, but you don't need to worry about that for a toy program like this one.