tehgeekmeister’s blog

January 12, 2008

better one line binary readers in haskell, thanks to commenters and redditors.

Filed under: programming — Tags: , — tehgeekmeister @ 6:38 pm

update to my previous post on binary readers.

from roconnor:

readBin s = x

[(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.

1 Comment »

  1. […] 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

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: