gpt4 book ai didi

haskell - 在函数内部使用 Haskell 函数

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

我的 Haskell 练习需要一些提示。

首先我必须实现一个程序,它检查一个整数是否为偶数......我的代码到目前为止,这个工作完美

isEven :: Int -> Bool
isEven 0 = True
isEven (-1) = False
isEven 1 = False
isEven x
|x<0 = isEven (x+2)
|x>0 = isEven (x-2)

接下来我必须使用这个函数来计算列表中的所有偶数。我到目前为止的代码:

countEven :: [Int] -> Int
countEven (x:xs) = (isEven x)
|True = 1 + countEven xs
|False = 0 + countEven xs

我想使用 isEven-returncode (True|False) 来确定是否对我的 Int 进行计数。我不知道如何继续编写脚本。

在这种情况下它说

parse error on input '|'

我尝试了另一个脚本,但它给出了错误

Couldn't match expected type 'Int' with actual type 'Bool'.

因此函数 isEven 正在运行,但我不知道如何将“True”语句转换为我的 if 语句。

最佳答案

以下任何一项工作:

countEven (x:xs) = if isEven x then 1 + countEven xs else 0 + countEven xs
countEven (x:xs) = (if isEven x then 1 else 0) + countEven xs
countEven (x:xs) = case isEven x of
True -> 1 + countEven xs
False -> 0 + countEven xs
countEven (x:xs)
| isEven x = 1 + countEven xs
| otherwise = 0 + countEven xs

关于haskell - 在函数内部使用 Haskell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936746/

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