不确定递归排序功能?

时间:2017-02-14 05:17:41

标签: f#

我只想了解这个功能发生了什么,特别是第三种情况。谢谢!

// Note, false to avoid BOM marker which breaks some clients not expecting BOM for utf-8
var utf8 = new UTF8Encoding(false);
return WebOperationContext.Current.CreateTextResponse(
    json, 
    "application/json; charset=utf-8",
    utf8
);

1 个答案:

答案 0 :(得分:3)

F#中的::运算符是一个列表运算符,通常如下所示:

head :: rest

此处,head是列表的第一项,rest是列表的其余部分。即,

let rest = [2; 3; 4]
let head = 1
head :: rest  // Has the value [1; 2; 3; 4]

请注意不同类型:head单项rest项目列表

现在,::运算符可以在模式匹配中用作实际构建列表的运算符。它具有相同的含义,但在模式匹配中,你只是说“匹配如果列表具有这种形状”,而在模式匹配语法之外,你会说“ make 列表中有这个形状“。所以在模式匹配中,你有:

let describe lst =
    match lst with
    | [] -> "Empty list"
    | head::rest -> sprintf "Head is %A and rest is %A" head rest
describe [1; 2; 3; 4]
// Result: "Head is 1 and rest is [2; 3; 4]"

请注意,只有一个项目的列表完全有效,以匹配head::rest模式,在这种情况下,rest将只是一个空列表:

let describe lst =
    match lst with
    | [] -> "Empty list"
    | head::rest -> sprintf "Head is %A and rest is %A" head rest
describe [1]
// Result: "Head is 1 and rest is []"

::运算符也可以多次应用:

let describe lst =
    match lst with
    | [] -> "Empty list"
    | [x] -> sprintf "List of just one item, %A" x
    | first::second::rest -> sprintf "First item is %A and second item is %A and rest is %A" first second rest
describe [1; 2; 3; 4]
// Result: "First item is 1 and second item is 2 and rest is [3; 4]"

请注意我是如何为一个项目列表添加案例的?这是因为如果您将列表与形状first::second::rest匹配,如果列表至少包含两个项目,则匹配。只有一个项目的列表不会将任何内容放入second,因此不匹配。如果我在最新的例子中省略了[x]模式,编译器会警告我匹配表达式不完整。

现在我们可以看到match表达式的最后一行正在做什么:

| x1::x2::xs -> if x1 <= x2 then x1 :: sort (x2::xs)
                            else x2 :: sort (x1::xs)

模式是说“如果此列表中至少有两个项目匹配。请调用第一项x1,然后调用第二项x2,然后调用列表的其余部分{{ 1}}“。然后它比较列表的第一个和第二个项目。两个中较小的一个被视为函数输出的第一项,函数输出的“rest”是“取大项,将其添加到xs列表中,然后将其传递给{ {1}}功能“。

顺便问一下,你能发现这个功能中的错误吗?如果没有,请考虑它将如何处理以下列表:

xs

sort函数的输出与该输入有什么关系?