我想编写一个具有两个where子句的Haskell函数,但从编译器中收到此错误:
输入中的语法错误(意外的符号“ changeNew”)
changeItem oPos nPos (x:xs)
| oPos < nPos = changeOld
| oPos > nPos = changeNew
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
where changeOld
| oPos == 0 = (xs !! nPos) : changeItem x (nPos-1) xs
| nPos == 0 = oPos : xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
changeNew
| oPos == 0 = nPos : xs
| nPos == 0 = (xs !! oPos) : changeItem (oPos-1) x xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
代码有什么问题?为什么不能声明两个where子句?
where
子句中定义的名称需要在左侧对齐,像这样
changeItem oPos nPos (x:xs)
| oPos < nPos = changeOld
| oPos > nPos = changeNew
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
where
changeOld
| oPos == 0 = (xs !! nPos) : changeItem x (nPos-1) xs
| nPos == 0 = oPos : xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
changeNew
| oPos == 0 = nPos : xs
| nPos == 0 = (xs !! oPos) : changeItem (oPos-1) x xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
尽管更“常用”的Haskell样式会将所有内容移至左侧,以防止您的代码进入右下角。
changeItem oPos nPos (x:xs)
| oPos < nPos = changeOld
| oPos > nPos = changeNew
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
where
changeOld
| oPos == 0 = (xs !! nPos) : changeItem x (nPos-1) xs
| nPos == 0 = oPos : xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
changeNew
| oPos == 0 = nPos : xs
| nPos == 0 = (xs !! oPos) : changeItem (oPos-1) x xs
| otherwise = x : changeItem (oPos-1) (nPos-1) xs
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句