Home > other >  How to use the contents of a list to output a new list?
How to use the contents of a list to output a new list?

Time:11-14

I am looking to find a way on how to use the contents of a list of one type, to output a list of another for use in a game.

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

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

So if quickGame N [S,W,E,N,N] was the input, I would receive in return [Back,Right,Back,Left,Forward].

Any help would be appreciated. I have tried an if then else to go through the list to output the second, but there must be a cleaner way?

CodePudding user response:

First, you're going to run into a conflict with the built-in Left and Right constructors for the Either type, so let's redefine:

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

Then, let's define a helper that compares our current direction with the new direction, and returns an appropriate step. It's tedious, but relatively straightforward.

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

Now, quickGame can be expressed recursively by comparing the current direction (first argument) to the next direction (first element of the second argument) and outputting the appropriate step, and then recursively calling quickGame with the new direction as "current":

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

The final code:

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]
  • Related