Haskell中if then else语句后出现解析错误是什么原因?
问题原因
直接触发解析错误的两个语法问题
- 括号不匹配:
replace函数else分支末尾的代码drop (snd (convert (xs)) ys缺少2个右括号,用于闭合snd函数和drop第一个参数的括号,修正后应为drop (snd (convert xs)) ys,同时可删除xs外层多余的括号让代码更简洁。 - 缩进不符合Haskell语法规范:
if对应的then、else块换行后,缩进级别需要大于等于if关键字的缩进级别,你当前代码中then和else都和if齐平,也会触发解析错误。
其他潜在的运行/编译错误
- 代码中调用了
translate函数,但你没有给出该函数的定义,后续编译会报未定义标识符错误。 convert函数仅支持处理长度为1的列表,如果传入replace的第一个参数[(Int,Int)]长度不等于1,运行时会触发模式匹配失败错误。
修正后可通过编译的示例代码(需自行实现translate函数)
replace :: [(Int,Int)] -> String -> String replace xs ys = if translate (manipulator (fst (convert xs)) (snd (convert xs)) ys) /= "" then take (fst (convert xs)) ys ++ (manipulator (fst (convert xs)) (snd (convert xs)) ys) ++ drop (snd (convert xs)) ys else take (fst (convert xs)) ys ++ stjerner (snd (convert xs) - fst (convert xs)) ++ drop (snd (convert xs)) ys stjerner :: Int -> String stjerner 0 = "" stjerner int | int > 0 = "*" ++ stjerner (int -1) manipulator:: Int -> Int -> String -> String manipulator low high xs = take high (drop low xs) convert :: [a] -> a convert [a] = a
内容的提问来源于stack exchange,提问作者Magnus
相关产品推荐
相关产品推荐

