如何编写SML函数统计布尔列表中true的出现次数?
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
foldliterates over the list from left to right, using0as the initial count.- For each element
xin the list:- If
xistrue, we increment the accumulated countyby 1. - If
xisfalse, we keep the accumulated countythe same.
- If
- At the end of the iteration,
foldlreturns the total count oftruevalues.
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

