直接使用递归,写一个函数truesAndLength : bool list -> int * int
那
返回列表的长度(在该对的第一个组件中)以及列表的数量
列表中正确的元素(在第二个组件中)。你的函数必须只迭代
遍历列表的元素一次。 (请勿使用 List 模块中的任何函数。)
到目前为止,这是我的代码:
let rec length bs =
match bs with
| [] -> 0
| b::bs -> 1 + length bs
let rec trues bs =
match bs with
| [] -> 0
| b::bs -> if b = true then 1 + trues bs else trues bs
let truesandlength bs =
let l = length bs
let t = trues bs
(l, t)
truesandlength [true; true; false]
这是通过我迭代列表 2 次来实现的,我不知道如何只迭代 1 次。有什么提示吗?
根据您的评论,我建议您考虑以下问题b::bs
case:
- Call
truesAndLengths
递归地位于列表的尾部。这给你tTail
(正确的数量)和lTail
(尾巴的长度)。
- Compute
t
and l
获取基于以下值的完整列表b
. (E.g. l
比 多 1lTail
.)
- Return
t, l
.
关键是要打电话truesAndLengths
仅在代码中的一处递归,将其传递到列表的尾部。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)