一个程序,用于检查数字列表是否为整数,然后将其放入列表中



所以我正在尝试构建一个程序来接收数字列表并检查它们是否是整数。如果是数字,请将它们放在结果列表中。 我尝试了类似的东西但没有工作(所有功能都只能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是一些RealFracb是一些Integral

请注意,如果您使用Data.Ratio/Rational来表示无损小数,则当denominator为 1 时,您就会知道某物是整数。

最新更新