2014-11-21 65 views
0

我需要計算列表中的值之間的值,即[135,136,138,140]將計數135-136,136-138,138-140之間的所有數字。輸入列表[135.2,135.3,137,139]將使用類型[Float] [Float] [Int]輸出[2,1,1]。到目前爲止,我有:計數箱的集合中的頻率

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

    count :: [Float] -> [Float] -> [Int] 
    count [] [] = [] 
    count [x,y] = [(x,y)] 
    count (x:y:ys) = (x,y):count (y:ys) 

    forEach fun lst = heightbetween op ([],lst) 
    where 
    op (start,[]) = Nothing 
    op (start,a:as) = Just (start++(fun a):as 
         ,(start++[a],as)) 

forPairs fun lst lst2 = map (map fst) 
        $ forEach (\(a,b)->(fun a b,b)) 
        $ zip lst lst2 

回答

0

你的count看起來很奇怪。它應該是這樣的:

-- count -> ranges -> data -> [counts] 
count :: [Float] -> [Float] -> [Int] 
count [] _ = []  -- no ranges given -> empty list 
count [_] _ = [] -- no ranges, but single number -> empty list 
count _ [] = []  -- no data given -> empty list 
count (x:y:xs) d = 
    (heightbetween x y d) : count (y:xs) d 

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

其他線路已過時。 然後調用

count [135,136,138,140] [135.2,135.3,137,139] 

[2,1,1] 
0

首先,確保你的範圍列表是爲了....

rangePoints = [135,136,138,140] 

orderedRangePoints = sort rangePoints 

接下來,你會發現它更容易的工作與實際範圍(你可以使用2元組(low,high)

ranges = zip orderedRangePoints $ tail orderedRangePoints 

您將需要一個INRANGE功能(一個已經存在於Data.Ix,但不幸的是它包含的上界,所以你不能用它)

inRange (low,high) val | val >= low && val < high = True 
inRange _ _ = False 

你也想訂購您的輸入點

theData = sort [135.2,135.3,137,139] 

除了這些,binCount函數很容易編寫。

binCount'::[(Float, Float)]->[Float]->[Int] 
binCount' [] [] = [] 
binCount' (range:rest) vals = 
     length valsInRange:binCount' rest valsAboveRange 
     where 
      (valsInRange, valsAboveRange) = span (`inRange` range) vals 

請注意,我定義了一個名爲binCount',不binCount功能。我這樣做是因爲我認爲這是一個不安全的函數,因爲它僅適用於有序的範圍和值....您應該通過編寫一個更安全的binCount函數來完成此操作,該函數將所有上面的東西放在where子句中。你也許應該添加所有類型和一些錯誤檢查(如果一個值超出所有範圍,會發生什麼?)。

+0

@Eugene Sh。我如何計算大於140且小於135的值?它應該是模擬[從這裏開始,但我仍然得到同樣的錯誤 – caz 2014-11-28 14:51:18