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

Haskell中如何实现自定义Numbers数据类型的整数列表分类函数

实现说明

原有代码存在两个核心问题:

  • 空列表分支返回[],和函数声明的返回值类型Numbers不匹配
  • 非空分支逻辑错误,误将记录类型的字段更新当成了列表拼接操作

正确的递归实现如下:

data Numbers
  = Numbers{
      pos  :: [Int]
    , neg  :: [Int]
    , nul  :: [Int]
    } deriving Show

numList :: [Int] -> Numbers
-- 边界条件:空输入返回三个字段均为空的Numbers实例
numList [] = Numbers [] [] []
numList (x:xs) = 
  -- 先递归处理剩余元素得到分类结果
  let rest = numList xs
  in case compare x 0 of
    -- 等于0时更新nul字段,将当前x加入nul列表头部
    EQ -> rest { nul = x : nul rest }
    -- 大于0时更新pos字段
    GT -> rest { pos = x : pos rest }
    -- 小于0时更新neg字段
    LT -> rest { neg = x : neg rest }

也可以用foldr简化写法,避免显式递归:

numList :: [Int] -> Numbers
numList = foldr 
  (\x rest -> case compare x 0 of
    EQ -> rest { nul = x : nul rest }
    GT -> rest { pos = x : pos rest }
    LT -> rest { neg = x : neg rest })
  (Numbers [] [] [])

调用示例:
输入numList [1,-2,0,3,-5,0],输出结果为:
Numbers {pos = [1,3], neg = [-2,-5], nul = [0,0]}

内容的提问来源于stack exchange,提问作者Carlos Melo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 14:21:01