[Haskell-cafe] Comments and/or Criticisms

Devin Mullins twifkak at comcast.net
Mon Sep 10 01:43:53 EDT 2007


Alternatives; use your own judgment:

PR Stanley wrote:
> --count the occurrences of char in string
> countC :: Char -> [Char] -> Int
> countC x xs = sum [1 | c <- xs, c == x]

-- Direct mind-mapping of my brain:
countC x = length . filter (c ==)
-- Avoids constructing an intermediate list? I dunno. Looks stupid:
countC x = foldr (\c s -> s + if c == x then 1 else 0) 0

> --count occurrences of chars in string
> countCS :: [Char] -> [(Char, Int)]
> countCS xs = [(x, (countC x xs)) | x <- [' '..'z'], (countC x xs) > 0]

-- What popped into my imperative little brain
import Data.Map(assocs, empty, insertWith)
countCS str = assocs (countCS' str) where
   countCS' [] = empty
   countCS' (x:xs) = insertWith (+) x 1 (countCS' xs)
-- but Stuart's pointfree version is so much nicer.

Devin


More information about the Haskell-Cafe mailing list