Cloud Haskell中列表排序检查函数编译类型不匹配错误排查
Process Bool与Bool类型不匹配的错误 Hey there, let's break down this type mismatch error and fix it step by step.
错误原因分析
The error message spells out the core issue clearly: your sorted function is declared to return a Process Bool, but the expression you’ve written (same $ map (>0) $ filter (/=0) $ zipWith (-) a (tail a)) evaluates to a plain Bool value.
Cloud Haskell's Process is a monad designed to wrap distributed computation operations—you can’t return a pure value directly; you need to lift it into the Process context first. Your same helper is a pure function (it takes a list and returns a Bool), so the entire chain of pure functions produces a Bool, not the Process Bool your function signature promises.
解决方法
The simplest fix is to wrap your pure Bool result with return, which lifts it into the Process monad. Here's the corrected code:
sorted :: [Integer] -> Process Bool sorted a = return $ same $ map (>0) $ filter (/=0) $ zipWith (-) a (tail a) where same (x:xs) = and $ map (==x) xs
额外优化:处理边界情况
Your current code has a hidden problem: if you pass an empty list ([]) or a single-element list ([5]), calling tail a will throw an exception. Let's adjust the logic to handle these cases and make the code more concise:
sorted :: [Integer] -> Process Bool sorted [] = return True -- 空列表视为已排序 sorted [_] = return True -- 单个元素的列表视为已排序 sorted a = return $ all (>=0) diffs || all (<=0) diffs where diffs = zipWith (-) (tail a) a
This revised version checks if all consecutive differences are non-negative (ascending order) or non-positive (descending order)—it achieves the same goal as your original logic but avoids filtering out zero values and handles edge cases gracefully.
内容的提问来源于stack exchange,提问作者Shreyas Ramnath

