Function Haskell整数奇数校验器

Function Haskell整数奇数校验器,function,haskell,recursion,Function,Haskell,Recursion,我似乎被一个问题困住了,不知道如何解决这个问题,也不知道我现在的代码有什么错 我必须编写一个名为odddights的函数,它接受一个整数参数并返回一个布尔结果。当且仅当参数是具有奇数位数的正整数时,它应返回True。如果参数为零或负,则函数应停止并显示错误消息 此外,无法将参数转换为字符串。必须使用递归。 我有一种感觉,每个数字可以递归地存储在一个列表中,然后列表的长度可以决定答案 到目前为止,我有: oddDigits :: Integer -> Bool lst = [] od

我似乎被一个问题困住了,不知道如何解决这个问题,也不知道我现在的代码有什么错

我必须编写一个名为odddights的函数,它接受一个整数参数并返回一个布尔结果。当且仅当参数是具有奇数位数的正整数时,它应返回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 
odddights::Integer->Bool
lst=[]
奇数
|(x<0)| |(x==0)=错误
|x`mod`10++lst++odddights(x`div`10)
|长度(lst)`mod`2/=0=True
|否则=假

抱歉,如果代码看起来很糟糕。我是哈斯克尔的新手,还在学习。我到底做错了什么?我怎样才能纠正它

首先,这似乎是一件很奇怪的事情。也许你做错了什么是要考虑这个问题…<


但是如果你坚持,你想知道一个数字为奇数的整数的性质。。。哦,好吧。还有很多地方可以改进。对于初学者来说,
(x<0)|(x==0)
不需要括号–
转换为数字列表,然后查找列表长度的一般方法没有问题。实际上,错误的地方是试图将所有内容塞进一个函数中。正如您第一手发现的,这使得调试非常困难。函数式编程最适用于非常小的函数

如果您分离出将整数转换为数字列表的责任,使用类似于的
digs
函数,则算法的其余部分将简化为:

oddDigits x | x <= 0 = error
oddDigits x = odd . length $ digs x

odddights x | xleftaroundabout的最终答案非常好,但是对于2、3和23这样的数字它就失败了。这里有一个解决方案

oddDigits x 
  | x <= 0     = error "blearg"
  | x < 10     = True
  | otherwise  = not . oddDigits $ x`div`10
其中
odddights'::Integer->Integer->Integer

oddDigits x 
 | x <= 0                      = error "blearg"
 | length (show x)`mod`2 /= 0  = True
 | otherwise                   = False 
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
oddDigits x | x <= 0 = error
oddDigits x = odd . length $ digs x
oddDigits x 
  | x <= 0     = error "blearg"
  | x < 10     = True
  | otherwise  = not . oddDigits $ x`div`10
oddDigits :: Integer -> Bool
oddDigits x
   | x <= 0 = False
   | otherwise = oddDigits' True x

oddDigits' :: Bool -> Integer -> Bool
oddDigits' t x
   | x < 10 = t
   | otherwise = oddDigits' (not t) $ x `div` 10
oddDigits x
   | x <= 0 = False
   | otherwise = odd . oddDigits'' 1  $  x