所以我正在尝试构建一个程序来接收数字列表并检查它们是否是整数。如果是数字,请将它们放在结果列表中。 我尝试了类似的东西但没有工作(所有功能都只能mylist
工作(
numberisInteger number = number == fromInteger(round number)
one :: Float -> [Float]
one x = if numberisInteger x then [x] else []
two xs = [one x | x <- xs]
toint :: [Float] -> [Int]
toint = roundd
roundd xs = [round x | x <- xs]
mylist xs = [toint x | x <- xs]
main :: IO ()
main = return ()
代码所做操作的描述:numberisIntger
函数,检查一个数字是否整数并返回真或假,一个是函数它的参数,如果它的整数,那么它把它放在一个列表中,如果不是,它给出一个空的,两个函数就像一个,但作为一个理解,toint
函数隐藏浮点到整数的列表。
给定你的函数(使用truncate
而不是round
(,似乎你所需要的只是filter
:
isInteger :: RealFrac a => a -> Bool
isInteger x = fromIntegral (truncate x) == x
integers :: RealFrac a => [a] -> [a]
integers = filter isInteger
RealFrac a => a
可能是Float
的,也可能是Double
的。由于RealFrac
的舍入函数没有进一步的限制,因此此函数也不需要:a
是一些RealFrac
,b
是一些Integral
。
请注意,如果您使用Data.Ratio
/Rational
来表示无损小数,则当denominator
为 1 时,您就会知道某物是整数。