gpt4 book ai didi

list - 合并两个列表

转载 作者:行者123 更新时间:2023-12-03 23:46:40 25 4
gpt4 key购买 nike

我希望以纯函数方式合并 F# 中的 2 个列表。我很难理解语法。

假设我有一个元组 ([5;3;8],[2;9;4])
当我调用该函数时,它应该返回 [5;2;3;9;8;4]
这就是为什么我到目前为止,这是错误的,我敢肯定。如果有人能以简单的方式解释它,我将不胜感激。

let rec interleave (xs,ys) = function
|([], ys) -> ys
|(x::xs, y::ys) -> x :: y:: interleave (xs,ys)

最佳答案

你的功能几乎是正确的。 let f = functionlet f x = match x with 的简写所以你不需要显式参数。此外,您的算法需要一些调整。

let rec interleave = function //same as: let rec interleave (xs, ys) = match xs, ys with
|([], ys) -> ys
|(xs, []) -> xs
|(x::xs, y::ys) -> x :: y :: interleave (xs,ys)

interleave ([5;3;8],[2;9;4]) //output: [5; 2; 3; 9; 8; 4]

关于list - 合并两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9090799/

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