You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloud Haskell中列表排序检查函数编译类型不匹配错误排查

解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:22:22