Reputation: 709
First things first, I know how to append to a list in f#. If I have list = [1;2;3]
then I can I can do something like 5 :: list
and it will give me a new list [5;1;2;3]
.
I have written a function however that uses the exact same syntax but instead appends it to the back of the list, and I can't for the life of my figure out why. Can someone please explain to me why the function I wrote appends and item to the back of my list instead of the front?
let menu = [("pizza",17);("hotdog",5);("burger", 12);("drink",3);("milkshake",4)]
let rec insert dict key value =
match dict with
| (k,v) :: tl when k = key -> (k,v)::tl
| (k,v) :: tl -> (k,v)::insert tl key value
| [] -> (key,value) :: []
> insert menu "bacon" 22;;
val it : (string * int) list =
[("pizza", 17); ("hotdog", 5); ("burger", 12); ("drink", 3);
("milkshake", 4); ("bacon", 22)]
I don't really care one way or the other where it gets added to my list, I just don't understand why it's going on the end when I'm using the cons operator.
Upvotes: 2
Views: 1759
Reputation: 4488
Your insert
is a recursive function. You go through each element until you hit the bottom the empty list. If you didn't found the element, then you return a one-element list with the element added. Because your are at the bottom, now all elements before you walked through your list gets added on top of this.
So overall, your new item gets added at the the end, or appended.
Upvotes: 4
Reputation: 10624
You are always inserting the new pair in front of an empty list, which is the last tail at the end of the actual list.
So if we consider this example:
insert [(1, 2)] 3 4
// Returns [(1, 2); (3, 4)]
[(1, 2)]
can also be written like this:
(1, 2) :: []
And your code is effectively doing this:
(1, 2) :: (3, 4) :: []
Upvotes: 4