indexing - SML: get index of item in list -


i'm new sml , i'm attempting index of item in list. know using list.nth give me value of item @ index position, want index value. there may built in function i'm not aware of. in case, list not contain duplicates if item in list index, if not returns ~1. here code have far. works, don't think clean:

val l=[1,2,3,4,5]; val m=length l-1; fun index(item, m, l)=if m<0 ~1 else     if list.nth(l, m)=item m else index(item,m-1,l); 

to elaborate on previous comment, suggest changes implementation fits better in ml idiom:

fun index(item, xs) =   let     fun index'(m, nil) = none       | index'(m, x::xr) = if x = item m else index'(m + 1, xr)   in     index'(0, xs)   end 

the individual changes are:

  • have index return value of type int option. none means item not in list, some i means in list, , index of first occurrence i. way, no special values (~1) need used , function's intended usage can inferred type.
  • hide parameter m renaming function index' , wrapping outer function index calls appropriate arguments. prime character (`) indicates auxiliary values.
  • use pattern matching on list individual elements, eliminating need list.nth.

also note commonly, function , variable names begin lowercase letter (index rather index), while capital letters used constructor constants (some) , like.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -