gpt4 book ai didi

list - 有没有办法在递归时将列表的长度保存在变量中?

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

假设我有一个递归函数,它接受两个列表并返回一个 int,如下所示

fn ys (x:xs) 
| --some condition = original length of (x:xs)
| otherwise = fn ys xs

如果条件一为真,我需要返回输入列表的原始长度(在递归弄乱它之前)。有没有办法保存原来的长度?

最佳答案

您可以使用“worker”函数(传统上称为 go)进行递归,它允许您引用原始参数并定义额外的变量:

fn ys xs' = go xs'
where
l = length xs'
go (x:xs)
| --some condition = l
| otherwise = go xs

您可能还想要一个 go [] 的保护套。

关于list - 有没有办法在递归时将列表的长度保存在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29382195/

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