Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

recursion - Explanation for group by 3 elements from a list function using FOLD in OCAML

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All groups is the final answer, current is the group of three elements filled while parsing the input and size is the number of elements actually in current I guess.

Do you know the behavior of fold_left?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...