gpt4 book ai didi

f# - 计算列表中元素的出现

转载 作者:行者123 更新时间:2023-12-03 15:04:11 25 4
gpt4 key购买 nike

我有一个整数列表,并且多次出现的任何整数都会连续执行此操作。我想将其转换为元组列表,其中包含每个对象及其计数。

我想出了以下内容,但是temp的返回类型存在问题:“类型'int'与类型'a list'不匹配”。但是,这三种返回类型在我看来是一致的。我做错了什么?如果我所做的不是很好的F#,并且应该以完全不同的方式进行,请也告诉我。

let countoccurences list =
match list with
| x::xs -> let rec temp list collecting counted =
match list with
| x::xs when x=collecting -> temp xs collecting counted+1
| x::xs -> (collecting,counted)::temp xs x 1
| [] -> (collecting,counted)::[]
temp xs x 1
| [] -> []

最佳答案

在这一行:

| x::xs when x=collecting -> temp xs collecting counted+1

编译器将您的代码解释为
| x::xs when x=collecting -> (temp xs collecting counted)+1

但是你想要的是
| x::xs when x=collecting -> temp xs collecting (counted+1)

但是,即使进行了此更改,您算法的一个问题是 temp函数不是尾部递归的,这意味着在长列表中调用它可能会导致堆栈溢出(例如 countoccurences [1..10000]在我的计算机上失败)。如果这对您很重要,那么您应该重写 temp helper函数以使其具有尾递归性。最简单的方法是添加一个累加的列表参数,然后反转列表。
let countoccurences list =
match list with
| x::xs ->
let rec temp list collecting counted acc =
match list with
| x::xs when x = collecting -> temp xs collecting (counted+1) acc
| x::xs -> temp xs x 1 ((collecting, counted)::acc)
| [] -> (collecting, counted)::acc
temp xs x 1 []
|> List.rev
| [] -> []

关于f# - 计算列表中元素的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5084053/

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