2014-11-20 73 views
0

我必須找到一個不高於給定值的高度。我已經找到代碼來完成一個整數列表。但我需要它接受一個浮點值,即countElems :: Float -> Heights -> Int。我知道我必須使用從整體來允許浮點值,但我不知道如何實現它。這是我到目前爲止有:找到一個不超過另一個值的浮點值haskell

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

什麼是'Heights'?你能否更詳細地描述你的問題,假設我們不知道你想解決的問題(因爲我們不知道)? – bheklilr 2014-11-20 19:43:20

+0

它是通過countElems 150(tall_short) – caz 2014-11-20 19:53:33

+0

導入的整數列表,你能解釋爲什麼以及如何做,因爲我的老師幾乎不會說英語,也不能教一個更好的園丁哭。 – caz 2014-11-20 19:55:29

回答

1

只要編輯countElems類型的註釋接受任何命令類型:

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

現在既適用IntFloatOrd型類的每個實例。

實際上,這是編譯器推斷的countElems的實際類型。您的版本僅限於a = Float

+1

這會比'countElems n xs = length'更加地道。過濾(n <)xs',作爲@caz的額外提示。 – bheklilr 2014-11-20 21:22:15

+0

謝謝,我會在早上起牀時嘗試有序的類型。謝謝你的幫助。這是我還沒有教過的新方法。 @bheklilr – caz 2014-11-20 23:26:01

0

我用它來工作:

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