gpt4 book ai didi

function - Haskell 函数根据给定的函数获取列表的最小值

转载 作者:行者123 更新时间:2023-12-04 14:46:10 26 4
gpt4 key购买 nike

我必须写一个像 minByFunction (\x -> -x) [1,2,3,4,5] 这样的函数,它给我一个答案 5。另一个例子是 minBy length ["a", "abcd", "xx"] 给我 "a"。
我虽然可以用这样的方法解决这个问题:

minBy :: (a -> Bool) -> [a] -> Int
minBy measure list =
case list of
[] -> 0
(x:xs:rest) -> if measure x > measure xs then minBy measure x:rest else minBy measure xs:rest

最佳答案

您需要为 (x:rest) 使用括号, 否则解释为 (minBy measure x) : rest .由于两次递归调用有minBy measure共同点,我们可以做一个 if … then … else …我们进行递归调用的列表的子句。
此外measure本身不应该返回 Bool ,您想将其映射到任何类型 b那是 Ord 的成员类型类。
您还交换了递归调用:以防万一measure x < measure xs ,那么你应该用 x:rest 递归反之亦然。
最后该函数应该返回一个 a对象,因此基本情况是单例列表,而不是空列表:对于空列表,没有最小值:

minBy :: Ord b => (a -> b) -> [a] -> a
minBy measure list =
case list of
[x] -> x
(x:x2:xs) -> minBy measure (if measure x > measure x2 then x2:xs else x:xs)

关于function - Haskell 函数根据给定的函数获取列表的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70009007/

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