您的promedio 函数在空输入时失败; promedio [],因为它试图除以零。
这里有两种考虑空列表的替代方法:
(* Using one traversal *)
fun average xs =
case foldl (fn (x, (sum, count)) => (x + sum, 1 + count)) (0, 0) xs of
(0, 0) => 0
| (x, y) => x div y
(* Using two traversals *)
val sum = foldl op+ 0
fun average [] = 0
| average xs = (sum xs) div (length xs)
您可以使用任何带有List.partition 的谓词对列表进行分区。
在您的情况下,谓词可能是x <= avg。
fun partition_average xs =
let val avg = average xs
in List.partition (fn x => x <= avg) xs end
请注意,如果我没有在fn x => ... 之外将average xs 绑定到avg,
(* Don't do this *)
fun partition_average xs =
List.partition (fn x => x <= average xs) xs
然后我将为xs 的每个元素重新计算average xs。
一个演示:
- partition_average [1,2,3,4,5]; (* avg being 3 *)
> val it = ([1, 2, 3], [4, 5]) : int list * int list
- partition_average [1,2,3,9]; (* avg being 3(.75) *)
> val it = ([1, 2, 3], [9]) : int list * int list