Convert hex to bin in Haskell

107 Views Asked by At

I want to convert hex to bin haskell and this is what I did but it seems wrong. Could anyone help please?

bin:: Char -> String
bin'0' = "0000"
bin'1' = "0001"
bin'2' = "0010"
bin'3' = "0011"
bin'4' = "0100"
bin'5' = "0101"
bin'6' = "0110"
bin'7' = "0111"
bin'8' = "1000"
bin'9' = "1001"
bin'a' = "1010"
bin 'b' = "1011"
bin'c' = "1100"
bin'd' = "1101"
bin'e' = "1110"
bin'f' = "1111"
bin j = error "Your input is not a hex digit"

hex2bin :: Show a => Handle -> [a] -> IO ()
hex2bin fh [] = return ()
hex2bin fh (x:xs) = do 
    hPutStr fh (show(x) ++ "\n")
    hex2bin fh xs
1

There are 1 best solutions below

0
On

In your hex2bin you never call bin. You call it on the elements, so:

hex2bin :: Handle -> String -> IO ()
hex2bin fh [] = return ()
hex2bin fh (x:xs) = do 
    hPutStrLn fh (bin x)
    hex2bin fh xs

You can work with mapM_ :: (Monad m, Foldable f) => (a -> m b) -> f a -> m ():

hex2bin :: Handle -> String -> IO ()
hex2bin fh = mapM_ (hPutStrLn fh . bin)