简体   繁体   English

Haskell:为函数列表参数中的每个元素执行函数

[英]Haskell: Perform function for each element in function list parameter

There is probably a simple answer to this, but I am new to Haskell.对此可能有一个简单的答案,但我是 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?有没有办法为移动列表中的每个元素调用play函数,以便下面的gameExample函数在每次移动后返回游戏板?

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:或者您可以使用foldl函数为您执行此操作:

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.还有Data.Foldable.foldl' ,它的性能通常比foldl更好,但是对于像这样的玩具程序,您无需担心这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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