gpt4 book ai didi

list - 满足 haskell 中大多数元素的函数

转载 作者:行者123 更新时间:2023-12-01 00:43:42 28 4
gpt4 key购买 nike

我需要编写一段代码,如果函数满足列表中的大多数元素,则返回 True,不满足其中的 false。例如:moreThan odd [1,2,3]True,但是 moreThan odd [1,2,3,4]。这是我的代码:

moreThan funkt xs
= let
control funkt n (x : xs)
= control (if .?. then n + 1 else n) xs
contol funkt _
= False
in
control funtk 0 xs

有人能告诉我如何控制它以及我应该在 中写什么吗?。谢谢!

最佳答案

您编写的函数将为所有参数返回 False,因为您总是在列表结束时返回 False

您编写的函数需要跟踪两个变量:处理的元素数和谓词为真的元素数。由于这段代码可能是家庭作业,我给你一个结构,你可以用它来编写函数。在--???处填写自己的代码。

moreThan :: (a -> Bool) -> [a] -> Bool
moreThan pred = go 0 0 where
-- procd: number of elements processed
-- holds: number of elements for which pred holds
go procd holds (x:xs) = go procd' holds' xs where
procd' = -- ???
holds' = -- ???
go procd holds [] = -- ???

如果您需要更多提示,请随时发表评论。


编写此函数的更惯用的方法是使用折叠:

moreThan pred = finalize . foldr go (0,0) where
-- process one element of the input, produce another tuple
go (procd,holds) x = -- ???
-- produce a boolean value from the result-tuple
finalize (procd,holds) = -- ???

关于list - 满足 haskell 中大多数元素的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10692668/

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