Histogram in Haskell [closed]

We can start by generating ranges required, and then map count function onto ranges to get list of partial functions, which finally can be applied on the given list.

ranges lim n = takeWhile (\(x,y) -> x < lim) [(k*n, (k+1)*n - 1) | k <- [0..]]

count (l,r) = length.filter (\x -> l <= x && x <= r)

histogram n xs = (map count range ) <*> [xs] where range =(ranges (maximum xs) n)

-- OR

histogram n xs = count <$> range <*> pure xs where range =(ranges (maximum xs) n)

--OR, if you are unfamiliar with applicatives

histogram n xs = go funcs
                   where range =(ranges (maximum xs) n)
                         funcs = (map count range)
                         go [] = []
                         go (f:fs) = (f xs): (go fs)

Leave a Comment