I need to create a function rec assoc (d,k,l) that takes a triple (d,k,l) where l is a list of key-value pairs [(k1,v1);(k2,v2);...] and finds the first ki that equals k. If such a ki is found, then vi is returned. Otherwise, the default value d is returned. it needs to be tail recursive
here is the function that I made:
let rec assoc (d,k,l) = match l with
|[]-> d
|(a,b)::t ->
if (a==k) then b
else assoc(d,k,t)
;;
my logic here is take the head of the list l and if the first part of the tuple in the list matches k, I return the second part of the tuple. If not then i want to call the function again on the tail of the list so it checks each element. If the entire list is traversed down to the empty list without finding a match, I want to return d. For some reason, it always returns d no matter what list I give it. What could be the reason for that.
heres some sample output it should give:
# assoc (-1,"jeff",[("sorin",85);("jeff",23);("moose",44)]);;
- : int = 23
# assoc (-1,"bob",[("sorin",85);("jeff",23);("moose",44)("margaret",99)]);;
- : int = -1
mine returns -1 for both
let rec assoc d k = function
. – nlucaroni