Search code examples
recursionfunctional-programmingsmlrefsmlnj

Recursive function that deals with "ref" in SML


This is my first recursive function; I'm new to the programming world. So, the code does really confuse me. I discovered that SML doesn't allow variable updating. So I learned to use ref, and that code was the result. But it is still wrong. Please tell me what's wrong with my code.

I expect this function to return how many times the second parameter appears as the second integer in each tuple of the list that is the first parameter.

fun number_in_month (lst: (int*int*int) list, month: int) =
  let 
    val dates = ref 0 : int ref;
  in 
    if null lst then 
      !dates
    else 
      let      
        val tl_ans = tl lst;
        val hd_ans = hd lst; 
      in
        let
          fun add_1(date : int*int*int) =
            if #2 date = month then (
              dates := !dates + 1; 
              !dates
            )
            else 
              !dates;
         in
           add_1(hd_ans) 
         end
          
         number_in_month(tl_ans, month);
       end 

Solution

  • You should not be using ref, :=, or !.

    The number of times it occurs is

    • If the list is empty, it is zero
    • Otherwise:
      • If the first element matches, it is one more than the number of occurrences in the list's tail
      • Otherwise, it is just the number of occurrences in the list's tail

    This is a very straightforward recursion with two conditionals, and no updating of variables.
    Translating to SML left as an exercise.
    (Look at, and read about, more examples of list recursion.)