gpt4 book ai didi

f# - 反转列表然后添加新项目

转载 作者:行者123 更新时间:2023-12-01 19:32:59 24 4
gpt4 key购买 nike

我正在尝试学习 F#,并且我正在尝试创建一些简单的函数作为学习的一部分。

我创建了一个函数,可以将一个项目添加到列表中,然后反转结果。这在 Visual Studio 的 F# 交互式窗口中非常有效

let addThenReverse n list =
match list with
| [] -> []
| _ -> n::list |> List.rev

addThenReverse 0 [1;2;3] //results in [3; 2; 1; 0]

但是我在编写一个函数来反转列表然后向其中添加项目时遇到了困难。

let reverseThenAdd n list =
match list with
| [] -> []
| _ -> List.rev list |> n::list

reverseThenAdd 9 [1;2;3] //desired result [3; 2; 1; 9]

编辑上述的期望结果应该是 [9; 3; 2; 1]。发现这一点的人干得好!

第二个函数无法编译,我收到警告“This expression was expected to have type 'a list -> 'b list but here has type 'c list'”

我尝试的任何变体似乎都会导致其他编译错误。我假设(但不知道如何)我需要使用作为“List.rev list”的结果创建的新列表,也许是通过将它分配给一个变量。

最佳答案

问题是您将反向列表传递给连接表达式,这会抛出编译器。你应该这样做:

let reverseThenAdd n list =
match list with
| [] -> []
| _ -> n :: (List.rev list)

reverseThenAdd 9 [1;2;3] //desired result [3;2;1;9]

这意味着您要将 n 添加到 (List.rev list)

产生的列表中

关于f# - 反转列表然后添加新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com