gpt4 book ai didi

返回两个输出的函数

转载 作者:行者123 更新时间:2023-12-02 22:13:01 24 4
gpt4 key购买 nike

我想创建一个产生两个输出的函数。请考虑以下示例:

我构建了两个函数,给定一个整数列表,返回偶数位置的元素和奇数位置的元素的列表。

let rec alternate1 lst =
match lst with
[] -> []
| [x] -> []
| x::y::xs -> y::(alternate1 xs)

let rec alternate2 lst =
match lst with
[] -> []
| [x] -> [x]
| x::y::xs -> x::(alternate2 xs)

这里一切都很好。现在,问题是:我想创建一个单个函数alternate,它返回两个带有签名alternate: int list-> (int list * int list)的列表.

let rec alternate lst =
match lst with
[] -> []
| [x] -> []
| [x::y] -> [y]
(*My attempts:*)
| x::y::xs -> ((y::alternate xs), (x::alternate xs))
| x::y::xs -> [(y::alternate xs); (x::alternate xs)]
| x::y::xs -> ((y::alternate xs) && (x::alternate xs))

到目前为止,还没有解决方案有效。我很确定这个问题很愚蠢,但是我的 reference没有帮助我解决问题。

最佳答案

由于您递归地调用alternate,因此递归调用也会返回两个输出,因此您当然不能将该元组视为列表 - 作为在y::alternate xs中。

您必须首先将元组拆开,分别处理各个部分,然后在返回之前将它们重新组合成元组:

let nextXs, nextYs = alternate xs
x::nextXs, y::nextYs

然后,您的基本情况还应该返回两个输出 - 否则您的函数的返回类型不明确:

| [] -> [], []
| [x] -> [x], []
| [x; y] -> [x], [y]

(另请注意,您的匹配案例 [x::y] 实际上匹配一个列表列表,其中仅包含一个列表,其中第一个元素将被命名为 x,列表的尾部将被命名为 y。为了匹配恰好包含两个元素的列表,请使用 [x; y]x::y::[])

将其组合在一起:

let rec alternate lst =
match lst with
| [] -> [], []
| [x] -> [x], []
| [x; y] -> [x], [y]
| x::y::rest ->
let nextXs, nextYs = alternate rest
x::nextXs, y::nextYs

另外:从技术上讲,[x; y] 不需要基本情况​​,因为它可以被最后一个情况覆盖。

关于返回两个输出的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40636995/

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