如何使用列表的内容输出新的列表?

How to use the contents of a list to output a new list?

我正在寻找一种方法,了解如何使用一种类型列表的内容来输出另一种类型的列表以用于游戏。

data Dir   = N | E | S | W deriving (Show,Eq)
data Steps = Forward | Right | Back | Left deriving Show

quickGame :: Dir -> [Dir] -> [Steps]
quickGame d [] = []

所以如果 quickGame N [S,W,E,N,N] 是输入,我会在 return [Back,Right,Back,Left,Forward] 中接收。

如有任何帮助,我们将不胜感激。我已经尝试过 if then else 遍历列表以输出第二个,但必须有更简洁的方法吗?

首先,您将 运行 与 Either 类型的内置 LeftRight 构造函数发生冲突,因此让我们重新定义:

data Step = F | R | B | L deriving Show

然后,让我们定义一个 helper 来比较我们当前的方向和新的方向,以及 returns 一个适当的步骤。这很乏味,但相对简单。

step :: Dir -> Dir -> Step
step N N = F
step N E = R
step N S = B
step N W = L
step E N = L
step E E = F
step E S = R
step E W = B
step S N = B
step S E = L
step S S = F
step S W = R
step W N = R
step W E = B
step W S = L
step W W = F

现在,quickGame可以通过比较当前方向(第一个参数)和下一个方向(第二个参数的第一个元素)并输出适当的步骤来递归地表达,然后递归调用quickGame 新方向为“当前”:

quickGame :: Dir -> [Dir] -> [Steps]
quickGame cur (nxt:rest) = step cur nxt : quickGame nxt rest
quickGame _ [] = []

最终代码:

data Dir  = N | E | S | W deriving Show
data Step = F | R | B | L deriving Show

quickGame :: Dir -> [Dir] -> [Step]
quickGame cur (nxt:rest) = step cur nxt : quickGame nxt rest
quickGame _ [] = []

step :: Dir -> Dir -> Step
step N N = F
step N E = R
step N S = B
step N W = L
step E N = L
step E E = F
step E S = R
step E W = B
step S N = B
step S E = L
step S S = F
step S W = R
step W N = R
step W E = B
step W S = L
step W W = F

main = do
  print $ quickGame N [S,W,E,N,N]