Question

I'd declared the function below in the hope that if I am to overwrite some element in the list it actually works.But I am not completely sure if this is the right way.Any ideas different than mine will be appreciated

fun  foo (ls,n) =if ls = nil then nil else ( rev ( 1::List.rev ( List.take (ls,n-1 ))))@(List.drop (ls,n)

it should work like this

foo ([0,3,9],2) = [0,1,9]
Was it helpful?

Solution

(This code has one too few right parentheses.)

I don't see any big problems with this approach, especially if you want to avoid writing your own explicitly recursive solution. I don't think you need to do quite so much reversing if you add the new value to the beginning of the second part rather than the end of the first part. If you write your own function you can avoid some of the duplicate work. You might want to look at List.revAppend, which is intended for cases like this.

As a side comment: a list is not a particularly good data structure for updates at random locations.

OTHER TIPS

You're doing a lot of unnecessary work there. take, drop, rev and @ all involve traversing the list - you end up doing this five times, when you only need to do it once. As Jeffrey pointed out, you can eliminate the rev calls just by appending the 1 to the result of drop, but there's still room for improvement.

You should try writing your own recursive function which doesn't rely on anything in the List library. You really need to develop an intuitive grasp of recursive thinking to get anywhere with functional programming. The sequence of calls should look something like this:

  foo ([a,b,c,d], 4)
= a :: foo([b,c,d], 3)
= a :: b :: foo([c,d], 2) ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top