我對Haskell類有這個任務,但是我覺得這很困難。如果你能幫上忙。 您將得到一個迷宮棘手的haskell問題
maze = ["x xxx",
"x x",
"x x x",
"x x ",
"xxxxx"]
,你可以通過空格只能步行。你從(0,1)開始,該函數必須返回與方向的字符串逃過這是迷宮:
f - forward
r- turn right
l - turn left
如果你有你總是喜歡選擇正確轉發,並轉發到左。 對於當前的例子,答案是事先
data Direction = N | W | S | E deriving (Show,Eq)
maze = ["x xxx",
"x x",
"x x x",
"x x ",
"xxxxx"]
d = 's'
pos = (0,1)
fpath d pos | fst pos == (length maze - 1) = ""
| snd (pos) ==0 || (snd (pos) == ((length (maze!!0))-1)) = ""
| rightPossible d pos = "r" ++ (fpath (rightRotate d) pos)
| forwardPossible d pos = "f" ++ (fpath d (nstep d pos))
| True = "l" ++ fpath (leftRotate d) pos
where nstep :: Direction -> (Int, Int) -> (Int, Int) {-next step-}
nstep N (x,y) = (x-1,y)
nstep W (x,y) = (x,y-1)
nstep S (x,y) = (x+1,y)
nstep E (x,y) = (x,y+1)
rightPossible :: Direction -> (Int, Int) -> Bool
rightPossible N (x,y)= (maze !! x)!! (y+1) == ' '
rightPossible W (x,y)= (maze !! (x-1))!! y == ' '
rightPossible S (x,y)= (maze !! x)!! (y-1) == ' '
rightPossible E (x,y)= (maze !! (x+1))!! y == ' '
rightRotate :: Direction -> Direction
rightRotate N = E
rightRotate W = N
rightRotate S = W
rightRotate E = S
forwardPossible :: Direction -> (Int, Int) -> Bool
forwardPossible N (x,y)= ((maze !! (x-1))!! y) == ' '
forwardPossible W (x,y)= ((maze !! x)!! (y-1)) == ' '
forwardPossible S (x,y)= ((maze !! (x+1))!! y) == ' '
forwardPossible E (x,y)= ((maze !! x)!! (y+1)) == ' '
leftRotate :: Direction -> Direction
leftRotate N = W
leftRotate W = S
leftRotate S = E
leftRotate E = N
現在,哪裏是問題嗎?你已經做了什麼?你卡在哪裏? – Howard
使用[「牆壁追隨者」](http://en.wikipedia.org/wiki/Maze_solving_algorithm);) – Jacob
我在Haskell開始工作,我以前有過使用函數式語言的經驗。我知道我需要重新解決這個問題,但我無法在Haskel中實現它。 – munch