gpt4 book ai didi

list - 获取 Haskell 列表中下一个最小元素的索引

转载 作者:行者123 更新时间:2023-12-03 05:54:12 26 4
gpt4 key购买 nike

我是 Haskell 的新手。我很擅长命令式语言,但不擅长函数式语言。 Haskell 是我的第一个函数式语言。

我想弄清楚如何获取我定义的最小元素的列表中最小元素的索引。

让我通过例子来解释。

例如:

函数签名 minList::x -> [x]

let x = 2
let list = [2,3,5,4,6,5,2,1,7,9,2]

minList x list --output 1 <- is index

这应该返回 1。因为 at list[1] 是 3。它返回 1,因为 3 是 x (=2) 之后的最小元素。

let x = 1
let list = [3,5,4,6,5,2,1,7,9,2]
minList x list -- output 9 <- is index

它应该返回 9,因为在 list[9] 处是 2,2 是 1 之后的最小元素。x = 1 这是我定义的。

到目前为止我已经尝试过了。

minListIndex :: (Ord a, Num  a) => a -> [a] -> a
minListIndex x [] = 0
minListIndex x (y:ys)
| x > y = length ys
| otherwise = m
where m = minListIndex x ys

当我加载文件时出现此错误

• Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
minListIndex :: forall a. (Ord a, Num a) => a -> [a] -> a
at myFile.hs:36:17
• In the expression: 1 + length ys
In an equation for ‘minListIndex’:
minListIndex x (y : ys)
| x > y = 1 + length ys
| otherwise = 1 + m
where
m = minListIndex x ys
• Relevant bindings include
m :: a (bound at myFile.hs:41:19)
ys :: [a] (bound at myFile.hs:38:19)
y :: a (bound at myFile.hs:38:17)
x :: a (bound at myFile.hs:38:14)
minListIndex :: a -> [a] -> a (bound at myFile.hs:37:1)

当我像这样修改函数时

minListIndex :: (Ord a, Num  a) => a -> [a] -> a
minListIndex x [] = 0
minListIndex x (y:ys)
| x > y = 2 -- <- modified...
| otherwise = 3 -- <- modifiedd
where m = minListIndex x ys

我再次加载该文件,然后它编译并运行,但 ofc 输出不是所需的。

有什么问题

| x > y =  length ys
| otherwise = m

简而言之:基本上,我想找到最小元素的索引,但高于我在参数/函数签名中定义的 x 。

感谢您提前提供的帮助!

最佳答案

minListIndex :: (Ord a, Num  a) => a -> [a] -> a

问题是您试图返回泛型类型 a 的结果,但它实际上是列表中的索引。

假设您正在尝试评估 double 列表的函数。在这种情况下,编译器应该将函数的类型实例化为 Double -> [Double] -> Double 这是无意义的。

实际上,编译器注意到您正在返回从列表长度派生的内容,并警告您不可能将泛型类型 a 与具体的 Int 相匹配。

length ys 返回 Int,因此您可以尝试以下操作:

minListIndex :: Ord a => a -> [a] -> Int
<小时/>

关于你原来的问题,似乎你无法用简单的递归来解决它。考虑使用 accumulator 定义辅助递归函数。在您的情况下,它可以是一对 (min_value_so_far, its_index)

关于list - 获取 Haskell 列表中下一个最小元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749592/

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