找到一个不超过另一个值haskell的Float值

时间:2014-11-20 19:29:29

标签: haskell

我必须找到一个不高于给定值的高度。我找到了为整数列表执行此操作的代码。但我需要它接受一个浮动值,即countElems :: Float -> Heights -> Int。我知道我必须使用fromIntegral来允许Float值,但我不知道如何实现它。这就是我到目前为止所做的:

countElems :: Int -> [Int] -> Int
countElems n (x:xs) = fromEnum (n < x) + countElems n xs
countElems _ []     = 0

2 个答案:

答案 0 :(得分:1)

只需编辑countElems类型注释即可接受任何有序类型:

countElems :: Ord a => a -> [a] -> Int
countElems n (x:xs) = fromEnum (n < x) + countElems n xs
countElems _ []     = 0

现在,它适用于IntFloat以及Ord类型类的每个实例。

实际上,它是编译器推断出的countElems的实际类型。您的版本仅限于a = Float

答案 1 :(得分:0)

我用它来工作:

countElems :: Float -> [Float] -> Int countElems _ [] = 0 countElems n (x:xs) | n < x = 1 + (tallerthan n xs) | otherwise = tallerthan n xs