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

如何编写SML函数统计布尔列表中true的出现次数?

Fixing Your SML truecount Function

Hey there! I see where the issue is with your function—let's break it down and fix it.

The Problem in Your Code

Your current code uses foldl correctly in terms of the overall approach, but the anonymous function you passed to foldl is missing a critical part: the else branch of your if expression.

In SML, every if expression must have both a then and else branch because it's an expression that needs to return a value of a consistent type. Right now, when x is false, your function doesn't specify what to return, which causes a type mismatch error (and prevents the code from compiling properly).

Your original code:

fun truecount(lst) = foldl (fn (x,y) => if x=true then y+1) 0 lst;

The Fixed Version

We just need to add an else clause that returns the current count y when x is false. Also, since x is already a boolean value, we can simplify x=true to just x for cleaner code:

fun truecount(lst) = foldl (fn (x,y) => if x then y + 1 else y) 0 lst;

How This Works

  • foldl iterates over the list from left to right, using 0 as the initial count.
  • For each element x in the list:
    • If x is true, we increment the accumulated count y by 1.
    • If x is false, we keep the accumulated count y the same.
  • At the end of the iteration, foldl returns the total count of true values.

Alternative Recursive Implementation

If you're curious, here's a straightforward recursive version of the same function, which might help clarify the logic further:

fun truecount [] = 0
  | truecount (true::rest) = 1 + truecount rest
  | truecount (false::rest) = truecount rest;

This recursive approach pattern-matches on the list:

  • Empty list returns 0 (base case).
  • If the head is true, add 1 and recurse on the rest of the list.
  • If the head is false, just recurse on the rest of the list without changing the count.

内容的提问来源于stack exchange,提问作者B. Williams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:20