Skip to content

Instantly share code, notes, and snippets.

@abbradar
Last active August 29, 2015 14:14
Show Gist options
  • Save abbradar/5168ccd670cb0cbb1dba to your computer and use it in GitHub Desktop.
Save abbradar/5168ccd670cb0cbb1dba to your computer and use it in GitHub Desktop.
{-# LANGUAGE RecordWildCards #-}
import Data.Bits
import Control.Monad
import Control.Applicative
import Text.ParserCombinators.ReadP
import Numeric
binary :: (Read a, Num a) => ReadP a
-- 'pure' lifts Char into a String
binary = readS_to_P $ readInt 2 (`elem` ['0', '1']) (read . pure)
decimal :: (Eq a, Num a) => ReadP a
decimal = readS_to_P readDec
data Code = Code { n :: Int
, k :: Int
, bits :: [Integer]
}
deriving (Show)
code :: ReadP Code
code = do
n <- decimal
skipSpaces
k <- decimal
skipSpaces
-- We could check here if each bitstring is exactly of length k, but we are lazy
-- (<*) does some action and discards its result, instead returning result of its left argument.
-- It's essentially (<<)
bits <- forM [1..n] $ const $ binary <* skipSpaces
return Code { .. }
input :: ReadP (Code, Code)
-- input = (,) <$> code <* skipSpaces <*> code
input = do
a <- code
skipSpaces
b <- code
return (a, b)
main :: IO ()
main = do
stdin <- getContents
putStrLn $ show $ readP_to_S input stdin
> ./parse
2 7
1111001
1011011
3 1
1
1
1
[((Code {n = 2, k = 7, bits = [121,91]},Code {n = 3, k = 1, bits = [1,1,1]}),"")]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment