ocaml-programming

Simple OCaml programs
git clone git://git.laack.co/ocaml-programming.git
Log | Files | Refs | README

sum.ml (781B)


      1 (* 1
      2 
      3 NEW IDEA: pattern matching on a list. A list is either empty, written [], or a
      4 head element attached to a tail, written h :: t. Those are the only two shapes,
      5 so a match with those two cases covers everything.
      6 
      7     match lst with
      8     | [] -> ...
      9     | h :: t -> ...
     10 
     11 sum_list lst adds up a list of ints. The empty list sums to 0.
     12 
     13 sum_list [1; 2; 3] = 6, sum_list [] = 0, sum_list [7] = 7.
     14 
     15 *)
     16 
     17 (*
     18     since a list is either nil or a cons of elements with nil, we pattern match as such, knowing eventually that t will be []
     19     and that will call the recursive function one last time as the base case.
     20 *)
     21 
     22 let rec sum_list lst =
     23     match lst with
     24     | h :: t -> h + sum_list t
     25     | [] -> 0;;
     26 
     27 print_int (sum_list (10 :: 34 :: 34 :: []));;
     28 print_int (sum_list [1; 2; 3]);;