Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SML: How to append an element to a list in SML?

Tags:

sml

Is there an operator in SML which allows me to append to a list without having to create a new list? For example

I cant do this:

 [1,2,3]::1

but I can do this:

 [1,2,3]@[1]

which is odd as I have to create a list with 1 in it. Is there a better way of doing this?

like image 392
Har Avatar asked Feb 09 '17 22:02

Har


People also ask

How do I append to a list in R studio?

To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.

How do you find the nth element of a list in SML?

It is to write a function which takes in an int and a list, returns a specific element in the list on the index of that given int. As you see, it's exactly like the List. nth()-function.

How do I update a list in SML?

and the function is called as update(FLR, (2,3)); The new list should be [(1,1),(2,3),(3,9),(4,16),(5,25)] . Also, if the function is called as update(FLR, (6,36)); The new list should be [(1,1),(2,4),(3,9),(4,16),(5,25), (6,36)] .


2 Answers

You have to create a list with a one in it either way. The tail of the tail of the tail of [1,2,3,1] is [1]. So if you have [1,2,3,1] in memory, you also have [1] somewhere in memory.

So even if there were operator like [1,2,3] @:: 1, it wouldn't make a difference since it still needs to create a list with a one in it.

PS: The real issue with xs @ [x] isn't the creation of the list, but the fact that its runtime is in O(n) (as opposed to x :: xs, which is in O(1)). This is also an issue inherent in the nature of immutable singly linked lists and thus can't be helped, but it's why you generally should avoid appending to the end of a list like that.

like image 190
sepp2k Avatar answered Nov 15 '22 10:11

sepp2k


[1,2,3]::1 tries to append the int list [1,2,3] into the integer value 1, which is not possible as an integer cannot be appended to.
1::[1,2,3] however, is completely valid as the list [1,2,3] supports the appending operation. The evaluation rules for :: require t1 :: t1 list, where t1 is a value from type 1, and t1 list is a list of type 1, what you're doing is t1 list :: t1.
[1,2,3] @ [1] is valid because you're appending a list into a list.

like image 28
Selhar Avatar answered Nov 15 '22 11:11

Selhar