recursion - Standard ML - Return the index of the occurrences of a given value in a list -
i'm trying figure out how return list of indexes of occurrences of specific value in list. i.e. indexes(1, [1,2,1,1,2,2,1]); val = [1,3,4,7] int list
i'm trying figure out how lists work , trying better @ recursion don't want use list.nth (or library functions) , don't want move pattern matching quiet yet.
this have far
fun index(x, l) = if null l 0 else if x=hd(l) 1 else 1 + index(x,tl l); fun inde(x, l) = if null l [] else if x=hd(l) index(x, tl l) :: inde(x, tl l) else inde(x, tl l); index(4, [4,2,1,3,1,1]); inde(1,[1,2,1,1,2,2,1]);
this gives me [2, 1, 3, 0]. guess i'm having hard time incrementing things index. index function works correctly though.
instead make 2 passes on list: first add index each element in list, , second grap index of right elements:
fun addindex (xs, i) = if null xs [] else (hd xs, i) :: addindex(tl xs, i+1) fun fst (x,y) = x fun snd (x,y) = y fun indexi(n, xs) = if fst(hd xs) = n ... :: indexi(n, tl xs) else indexi(n, tl xs)
(i left out part of indexi
exercise.) addindex([10,20,30],0)
gives [(10,0),(20,1),(30,2)]
. can use addindex
, indexi
implement original index
function:
fun index(n, xs) = indexi(n, addindex(xs, 0))
when work, can try merge addindex
, indexi
1 function both.
however, want write pattern matching, see instance addindex
written using patterns:
fun addindex ([], _) = [] | addindex (x::xs, i) = (x,i) :: addindex(xs, i+1)
Comments
Post a Comment