use*_*703 2 haskell conditional-statements
我有一个Haskell代码的问题,我有以下内容:
takeMeHere cs m =
|(find (==E) cs == Nothing && (checkNextStep pozxCrt+1 pozyCrt m) == True) = (Just E,[(pozxCrt+1,pozyCrt)] ++ m)
|(find (==S) cs == Nothing && (checkNextStep pozxCrt pozyCrt-1 m) == True) = (Just S,[(pozxCrt,pozyCrt-1)] ++ m)
|(find (==W) cs == Nothing && (checkNextStep pozxCrt-1 pozyCrt m) == True) = (Just W,[(pozxCrt-1,pozyCrt)] ++ m)
|(find (==N) cs == Nothing && (checkNextStep pozxCrt pozyCrt+1 m) == True) = (Just N,[(pozxCrt,pozyCrt+1)] ++ m)
|otherwise = (Nothing,m)
where
pozxCrt=fst(head m)
pozyCrt=snd(head m)
checkNextStep x y m = if(find (== (x,y)) m == Nothing) then True
else False
Run Code Online (Sandbox Code Playgroud)
我得到了parse error on input "|".如果我用类似if if else的方式编写代码,那么......它的工作原理.但是我想用| 为了更紧凑的编码.这里似乎有什么问题?
要修复解析错误,请从第一行中删除=.=标志放在警卫之后.
接下来,你应该缩进"在哪里"
takeMeHere cs m
|(find (==E) cs == Nothing && (checkNextStep pozxCrt+1 pozyCrt m) == True) = (Just E,[(pozxCrt+1,pozyCrt)] ++ m)
|(find (==S) cs == Nothing && (checkNextStep pozxCrt pozyCrt-1 m) == True) = (Just S,[(pozxCrt,pozyCrt-1)] ++ m)
|(find (==W) cs == Nothing && (checkNextStep pozxCrt-1 pozyCrt m) == True) = (Just W,[(pozxCrt-1,pozyCrt)] ++ m)
|(find (==N) cs == Nothing && (checkNextStep pozxCrt pozyCrt+1 m) == True) = (Just N,[(pozxCrt,pozyCrt+1)] ++ m)
|otherwise = (Nothing,m)
where
pozxCrt=fst(head m)
pozyCrt=snd(head m)
Run Code Online (Sandbox Code Playgroud)
这将至少解析,但它不会编译.本(checkNextStep pozxCrt pozyCrt+1 m)应该是(checkNextStep pozxCrt (pozyCrt+1) m).
让我补充一点,你可以修复很多冗长的代码:
find (==E) cs == Nothing 可以改为 E `notElem` xx == True为xif x then True else False 可以改为 x[x]++y 可以改为 x:y(pozxCrt, pozyCrt) = head m或(pozxCrt, pozyCrt):_ = m结果是:
takeMeHere cs m
| E `notElem` cs && checkNextStep (pozxCrt+1) pozyCrt m = (Just E,(pozxCrt+1,pozyCrt):m)
| S `notElem` cs && checkNextStep pozxCrt (pozyCrt-1) m = (Just S,(pozxCrt,pozyCrt-1):m)
| W `notElem` cs && checkNextStep (pozxCrt-1) pozyCrt m = (Just W,(pozxCrt-1,pozyCrt):m)
| N `notElem` cs && checkNextStep pozxCrt (pozyCrt+1) m = (Just N,(pozxCrt,pozyCrt+1):m)
| otherwise = (Nothing,m)
where
(pozxCrt, pozyCrt) = head m
checkNextStep x y m = (x,y) `notElem` m
Run Code Online (Sandbox Code Playgroud)
你在守卫中有很多重复.很多重复是创建新功能的标志.
move E (x, y) = (x+1, y)
move S (x, y) = (x, y-1)
move N (x, y) = (x, y+1)
move W (x, y) = (x-1, y)
takeMeHere cs m
| canGo E = go E
| canGo S = go S
| canGo W = go W
| canGo N = go N
| otherwise = (Nothing,m)
where
pos = head m
canGo dir = dir `notElem` cs && checkNextStep (move dir pos) m
go dir = (Just dir, move dir pos:m)
checkNextStep (x, y) m = (x,y) `notElem` m
Run Code Online (Sandbox Code Playgroud)
下一步:find canGo [E,S,W,N]用来摆脱守卫:
takeMeHere cs m =
case find canGo [E,S,W,N] of
Just dir -> (Just dir, move dir pos:m)
Nothing -> (Nothing, m)
where ...
Run Code Online (Sandbox Code Playgroud)