首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Haskell函数检查数字是否为奇数,而不使用奇数函数

Haskell函数检查数字是否为奇数,而不使用奇数函数
EN

Stack Overflow用户
提问于 2016-04-13 09:12:41
回答 1查看 2.8K关注 0票数 2

有人能帮我吗?我试图编写一个函数,检查x是否为奇数,而不使用奇数函数。这样不管用,但我不知道为什么。

代码语言:javascript
复制
   ugerade :: Integral a => a -> Bool
   ugerade x
    |x elem oddList  = True
    |otherwise = False
    where
     oddList=[x | x<-[1,3..]]

错误

代码语言:javascript
复制
    Could not deduce (Num t0) arising from the literal ‘1’
from the context (Integral a)
  bound by the type signature for ugerade :: Integral a => a -> Bool
  at /Users/Mauritius/Desktop/Haskell/u02/2-2/funktionen.hs:24:11-33
The type variable ‘t0’ is ambiguous
Relevant bindings include
  oddList :: [t0]
    (bound at /Users/Mauritius/Desktop/Haskell/u02/2-2/funktionen.hs:29:4)
Note: there are several potential instances:
  instance Integral a => Num (GHC.Real.Ratio a)
    -- Defined in ‘GHC.Real’
  instance Num Integer -- Defined in ‘GHC.Num’
  instance Num Double -- Defined in ‘GHC.Float’
  ...plus three others
In the expression: 1
In the expression: [1, 3 .. ]
In a stmt of a list comprehension: x <- [1, 3 .. ]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-13 09:25:15

问题就在眼前

代码语言:javascript
复制
x elem oddList

要么应该说

代码语言:javascript
复制
elem x oddList

因为elem是一个函数elem :: Eq a => a -> [a] -> Bool,或者

代码语言:javascript
复制
x `elem` oddList

您正在使用backticks来指示infix函数应用程序的位置。

请注意,您的函数没有按您的意愿工作。对于奇数,它最终会返回True (尽管大参数需要很长时间),但是对于偶数,它永远不会返回,因为函数不能证明偶数永远不在列表oddList中。

还要注意的是

代码语言:javascript
复制
oddList = [ x | x <- [1,3..] ]

是多余的,你可以直接写

代码语言:javascript
复制
oddList = [1,3..]

相反,同时也写

代码语言:javascript
复制
f x | x `elem` oddList = True
    | otherwise        = False

是多余的,你可以直接写

代码语言:javascript
复制
f x = x `elem` oddList

甚至是

代码语言:javascript
复制
f x = x `elem` [1,3..]

代码语言:javascript
复制
f = (`elem` [1,3..])
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36593732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档