简体   繁体   English

附加到列表F#的开头

[英]Append to beginning of List F#

First things first, I know how to append to a list in f#. 首先,我知道如何附加到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] . 如果我有list = [1;2;3]那么我可以做类似5 :: 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. 我不太关心它被添加到我的列表中的方式或其他方式,我只是不明白为什么当我使用cons运算符时它会结束。

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)]也可以这样写:

(1, 2) :: []

And your code is effectively doing this: 你的代码实际上是这样做的:

(1, 2) :: (3, 4) :: []

Your insert is a recursive function. 您的insert是一个递归函数。 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. 总的来说,您的新项目会在最后添加或附加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM