我在Haskell班上完成了这项任务,但是我发现这很困难。如果可以帮助的话。
你被迷宫了

maze = ["x xxx",
        "x   x",
        "x x x",
        "x x  ",
        "xxxxx"]

而且你只能穿越太空。从(0,1)开始,该函数必须返回一个字符串,其中包含逃避迷宫的方向:
f - forward
r- turn right
l - turn left

而且,如果您有选择,那么您总是喜欢向右前进,然后向左前进。
对于当前示例,答案是ffllffrffrfflf
提前致谢
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

最佳答案

我看到的第一件事是,您有一个优先权问题。表达式(maze !! x)!! y-1解析为((maze !! x)!! y)-1,而您希望将其解析为(maze !! x)!! (y-1)。添加括号以解决此问题。

添加此代码后,尽管您的算法似乎已损坏,但是代码仍会编译。也许其他人可以帮助您。

一些编码建议:

  • 在适当的位置添加类型签名以简化调试。 (如果类型失败,则编译器将更有可能在正确的位置显示错误)
  • 使用模式匹配而不是多余的大小写语句。代替
    nstep d (x,y)   {-next step-}
                    | d == 'n' = (x-1,y)
                    | d == 'w' = (x,y-1)
                    | d == 's' = (x+1,y)
                    | d == 'e' = (x,y+1)
    


    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)
    
  • 编写自己的data类型,而不要依赖字符。例如,您可以为路线创建自己的数据类型:
    data Direction = N | W | S | E deriving (Show,Eq)
    
  • 10-08 12:35