'number_in_month exercise (smlnj how to iterate a value)

im new in functional programming but i have experience in imperative programming specially on java. i would like to ask how does a value iterate in smlnj i know that on java you can use varName += anyNumber or varName = varName + 1. on smlnj i dont know how to do this and my var value is not iterating here is a sample of my code. thanks in advance.

fun number_in_month (dates : (int*int*int) list , month : int) =
    let
      val total = 0;
    in
      let
        fun check(date : (int*int*int) list , m : int) =
            if #2(hd(date)) = m
            then total + 1  (* this is the problem in the code i don't know
                               how to iterate this like "varName += 1" in java *) 
            else check(tl(date),m)     
      in
        check(dates,month)
      end
    end

this program will check if the dates (on a list) entered exist on the month entered and will output how many dates exist on the month.

for example : number_in_month ([(year,month,day)],monthEntered) number_in_month([(2017,2,1),(2015,2,3),(2012,1,2)],2) output must be 2 because the first and second item in the list is equal to the monthEntered.

the problem in my code is it just output 1 even if the all of the dates i input is equal to the month i enter. i just want to know why it just output 1 and how should i fix it. Thanks in advance :D



Solution 1:[1]

Generally in a language that doesn't supply loops (for or while) your next choice should always be recursion. In this particular case recursive calls to this function should be how you "increment" the result.

Just think about the problem backwards, "It needs to return 1 in case there's a match, and 0 otherwise" -- this would mean that calling the function inside itself would potentially return a 1 twice, calling it 3 times would return a 1 three times etc. Now, it's only a matter of adding up all the successful times the recursive function call actually returns 1. And don't worry about infinite recursion, since it will return 0 otherwise and make the recursion tree collapse.

fun number_in_month(dates: (int * int * int) list, month: int) =
    if null dates
    then 0
    else
        if #2 (hd dates) = month
        then 1 + number_in_month(tl dates, month) (* <--this is where the magic happens *)
        else number_in_month(tl dates, month)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Absolute Virtue