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

Haskell递归实现列表查找首个大于参数元素位置问题求助

问题根源

你当前代码的核心缺陷是otherwise分支没有判断递归调用的返回值,直接执行+1操作:当列表中不存在符合条件的元素时,最底层递归返回-1,每一层回溯都会给这个-1加1,最终返回值等于列表长度 - 1,和预期的-1不符。

修复方案

你只需要在otherwise分支增加对递归返回结果的判断:如果递归返回-1,说明后续子列表没有匹配元素,当前层直接返回-1即可,否则才执行+1计数。

修复后的代码如下:

posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA [] _ = (-1) 
posicionPrecioMayorA (x:xs) a
    | x > a = 0
    | otherwise = let res = posicionPrecioMayorA xs a
                  in if res == (-1) then (-1) else 1 + res

测试验证

  • 匹配成功场景:posicionPrecioMayorA [10,15,30] 20 返回 2,符合预期
  • 无匹配场景:posicionPrecioMayorA [10,15,30] 100 返回 -1,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:39:03