update to my previous post on binary readers.
from roconnor:
readBin s = x
where
[(x,"")] = Numeric.readInt 2 (`elem` "01") Char.digitToInt s -- probably the best way of doing it; reinventing what's available in the standard libraries isn't a good thing.
and two from pjdelport:
readBin = foldM (\a d -> (a*2 +) <$> elemIndex d "01") 0 -- as elemIndex evaluates to a Maybe, (<$>) or fmap is necessary to lift the arithmetic section into the Maybe. bonus points for using Maybe instead of error.readBin = (foldl' ((+) . (*2)) 0 <$>) . mapM (`elemIndex` "01")— this version separates “parsing” and summing the values of each bit. otherwise same benefits as the previous versions.
that’s it for now.
[...] google results for “binary reader”, so i feel obligated to point out that i posted an update on this, with better versions thanks to commenters both here and on [...]
Pingback by one line binary reader in haskell « tehgeekmeister’s blog — January 13, 2008 @ 10:13 pm