[英]Compile Error in Haskell with recursive `let` function with `if then else`
[英]Haskell recursive function with if else block
嗨,我是Haskell的新手,正在我的函數doSomething中遇到此錯誤
有條件的意外分號:如果(solveMaze(x + 1)y a ey wasHere correctPath)然后執行{replaceNthcorrectPath! xy正確; 返回True}; 否則什么都不是,您是否打算使用-XDoAndIfThenElse?
我查了一下縮進,一切似乎都是正確的。
下面是我的代碼
replaceValue n newVal (x:xs)
| n == 0 = newVal:xs
| otherwise = x:replaceValue (n-1) newVal xs
doSomething :: Int -> Int -> Int -> Int -> [String] -> [[Bool]] -> [[Bool]] -> Bool
doSomething x y a b arr visited correct = do
if (x == a && y == b)
then do return True
else if (arr !! y !! x == 'A' || visited !! x !! y == True)
then do return False
else do
replaceValue visited !! x y True
if (x /= 0)
then do
if(doSomething (x-1) y a b arr visited correct)
then do
replaceValue correct !! x y True
return True
else do
Nothing
else if (x /= length arr !! 0)
then do
if(doSomething (x+1) y a b arr visited correct)
then do
replaceValue correct !! x y True
return True
else Nothing
else if (y /= 0)
then do
if(doSomething x (y-1) a b arr visited correct)
then do
replaceValue correct !! x y True
return True
else Nothing
else if (y /= length arr)
then do
if (doSomething x (y+1) a b arr visited correct)
then do
replaceValue correct !! x y True
return True
else Nothing
else Nothing
return False
謝謝!
問題出在代碼的這一部分
if(doSomething (x+1) y a b arr visited correct)
then do
replaceValue correct !! x y True
return True
else Nothing
最后一個else
應該比if
縮進更多。 一個額外的空間應該足夠了。
仍然,您的代碼有幾個問題。 您使用的是大量的do
S周圍,但你的函數的類型不使用任何單子。 我的建議:
您似乎堅持使用與命令式編程中使用的相同的代碼結構,這些命令結構通常很難翻譯成功能語言。 也許您應該先學習Haskell,然后做基本練習。 LYAH是一個受歡迎的教程網站。
對於此特定代碼,您需要Bool
的二維數組。 您可以使用列表列表對其進行建模,但是如果您需要隨機訪問該數組,則會導致性能下降。 我將使用向量代替,因為它們提供了快速的隨機訪問。
我不清楚您的功能正在嘗試執行什么操作。 如果使用可變向量的有狀態程序確實是最自然的選擇,我將使用State
monad或ST
monad對此進行編碼。 但是,在開始使用monad之前,我強烈建議您對語言的基礎知識有深入的了解。 LYAH僅在第12章和第13章中解釋了單子。
我建議這樣做是因為諸如
do replaceValue .....
return True
在功能世界中看起來毫無意義:它似乎試圖“修改”數組中的某些內容,這在非命令性語言中沒有意義。 如果不使用monad,可以將您的函數重寫為
type Grid = [[Bool]] -- or vectors...
doSomething :: Int -> Int -> Int -> Int -> [String] -> Grid -> Grid -> (Grid, Bool)
請注意,最終輸出不再是Bool
,而是一對所述Bool
和具有預期修改的新Grid
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.