sml recursive function example

The occurrences function takes two parameters, a list for the first one and an element of the list in the second. It returns the number of occurrences of the second parameter in the list.
nil means null list. if it’s null, return 0
| means or here is the function definition if the first parameter is not null
hd is a built in function that returns the first element of the list
tl is a built in function that returns all elements of the list but the first element
In the function definition, if the first element is equal to the second parameter, we have found 1 occurrence, then add 1, remove the first element and and recursively call the occurrences function again.

(*returns the occurrence of n in a list*)
fun occurrences(nil, n)=0
|   occurrences(ls, n) =
    if hd(ls)=n then occurrences(tl(ls),n) + 1
    else occurrences(tl(ls),n)+0;

(*Calling the occurrences function*)
occurrences([1,2,1,3,1,4,5,1,9],1);
occurrences(["a","b","c","d","a"],"a");
occurrences([1,2,3,4,5,6,7,8],9);

Output:

val occurrences = fn : ''a list * ''a -> int
val it = 4 : int
val it = 2 : int
val it = 0 : int
val it = () : unit

Search within Codexpedia

Custom Search

Search the entire web

Custom Search