简体   繁体   中英

Haskell: Perform function for each element in function list parameter

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM