gpt4 book ai didi

function - Haskell 整数奇数检查器

转载 作者:行者123 更新时间:2023-12-04 23:39:37 26 4
gpt4 key购买 nike

我似乎被困在一个问题上,不知道如何解决它或我当前的代码做错了什么。

我必须编写一个名为oddDigits 的函数,它接受一个整数参数并返回一个 bool 结果。当且仅当参数是奇数位数的正整数时,它才应该返回 True。如果参数为零或负数,则函数应停止并显示错误消息。

此外,不能将参数转换为字符串。必须使用递归。
我有一种感觉,每个数字都可以递归地存储在一个列表中,然后列表的长度可以确定答案。

到目前为止,我有这个:

oddDigits :: Integer -> Bool 

lst = []

oddDigits x
| (x < 0) || (x == 0) = error
| x `mod` 10 ++ lst ++ oddDigits(x `div` 10)
| length(lst) `mod` 2 /= 0 = True
| otherwise = False

抱歉,如果代码看起来很糟糕。我是 Haskell 的新手,仍在学习。我到底做错了什么,我该如何纠正?

最佳答案

首先,这似乎是一件很奇怪的事情。也许你做错的是永远考虑这个问题......

XKCD Wikipedia printer

但是如果你坚持你想知道一个具有奇数位数的整数的属性......哦,好吧。有很多可以改进的地方。对于初学者,(x < 0) || (x == 0)不需要括号 – <== (中缀 4)绑定(bind)比 || 更紧密.如果您对此不确定,可以随时询问 GHCi:

Prelude> :i ==
class Eq a where
(==) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 ==
Prelude> :i ||
(||) :: Bool -> Bool -> Bool -- Defined in ‘GHC.Classes’
infixr 2 ||

但是这里你不需要 ||无论如何,因为有一个专门的运算符用于小于或等于。因此你可以写
oddDigits x 
| x <= 0 = error "bla bla"
| ...

然后, you can将数字“转换”为字符串。转换为字符串通常是一件非常令人不快的事情,因为它会将所有结构、类型检查等抛到窗外;但是,“位数”基本上是字符串的属性(十进制扩展),而不是数字本身,因此对于此特定任务来说这并非完全不明智。这会起作用:
oddDigits x 
| x <= 0 = error "blearg"
| length (show x)`mod`2 /= 0 = True
| otherwise = False

但是,这有点冗余部门冗余。您正在检查是否有 True , 然后给 True结果......为什么不把它放在一个子句中:
oddDigits x 
| x <= 0 = error "blearg"
| otherwise = length (show x)`mod`2 /= 0

这也许实际上是最好的实现。

对于任何适当的、明智的任务,我不建议走字符串路线。递归更好。这是它的样子:
oddDigits 1 = True
oddDigits x
| x <= 0 = error "blearg"
| otherwise = not . oddDigits $ x`div`10

关于function - Haskell 整数奇数检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885270/

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