0

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.

user4075830
  • 87
  • 1
  • 2
  • 11

2 Answers2

0

You have to realise that values are not mutable in ML. This means that once you create a value, you can't change it!

So if we have these two statements

x = [2,3,4]
y = 1::x

then y and x live in seperate memory locations on the computer.


What you can do is the following:

fun swapFirst []      y = raise Empty
  | swapFirst (x::xs) y = y::xs
val test_swapFirst_00 = [1,2,3,4] = swapFirst [2,2,3,4] 1

which will swap the first element of a list out with something else.


Now I have a feeling that this could be for an answer for some course work, so I'm not going to give a complete code that solves your problem, but this information should at least clear some things up, and make it easier for you to solve the problem!

RasmusWL
  • 1,573
  • 13
  • 26
  • What trouble me is how to change a variable I dont know if l @ [i] will pull the variable at i or not ? – user4075830 Oct 27 '14 at 16:01
  • @user4075830: You cannot "change a variable" in ML. There is simply no syntax to do that in the language. – newacct Oct 28 '14 at 01:45
0

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)
user4075830
  • 87
  • 1
  • 2
  • 11