Search code examples
listvariablessmlsmlnj

Change a variable in standard ml list


I wonder when working with list in ml, how to change a variable with specific location of the list. For instance, when I have a list [1,2,3,4], I want to change the list to [1,2,5,4] with the 5 subtitle for the 3. What i'm thinking is to write a function that take a location, the variable and the list, return the new list with the update variable. For example,

change(i, var, list) = let val valup = var in (list @ [i]) end

So with this code, if my input is change(2, 5, [1,2,3,4]), my out put will be [1,2,3,4,2] which incorrect compare to [1,2,5,4]. I'm new with ml and not good with the list setup in the language so any help would be really appreciate.


Solution

  • I come up with the solution for the problem.

    fun change(i,v,[]) = raise Error
    |   change(0, v, x::xs) =  v :: xs
    |   change(i, v, x::xs) =  if i < 0 then raise Error
                                else  x :: change((i-1), v, xs)