I have a piece of code that does the following: group 3 elements of a list of n elements. The main function is called group_by_3
. For example, executing group_by_3 [1;2;3;4;5;6;7]
will give me ([1;2;3],[4;5;6],[7])
.
let group_by_3 lst =
let accum = ( [], [], 0 )
in
let f (all_groups, current_group, size) x =
if size = 3
then ( (List.rev current_group) :: all_groups,
[x], 1 )
else ( all_groups, x::current_group, size+1)
in
let (groups, last, _) = List.fold_left f accum lst
in List.rev ( List.rev last :: groups)
I don't really understand why this works (it is provided in class).
- What are all_groups, current_group, size?
What does this do?
if size = 3
then ( (List.rev current_group) :: all_groups,
[x], 1 )
else ( all_groups, x::current_group, size+1)
Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…