Reputation: 1
I want to accept 5 values from the user. However, in my code (below) if I enter a list like [1,2,3,4,5]
I get an error. This code only accepts inputs of the form [999]
, for example.
Does anyone know how to fix this problem?
putStrLn("Enter 5 binary numbers [,,] : ")
input<-getLine
let n=(read input)::[Int]
let result = convertionTO binaryToDec n
putStrLn(show result)
In the above code, the line let n=(read input)::[Int]
will just accept the user input, [999]
or whatever, as one input. Is there a way to enter a list of values?
With the line let result = convertionTO binaryToDec n
I'm trying to convert here list of binary values to decimal
Upvotes: 0
Views: 191
Reputation: 12749
You could put a newtype
wrapper around an Integer
to give it its own Read
and Show
instances. That way, you can still use the list parser, but substitute your own parser for the elements:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Numeric ( readInt, showIntAtBase )
import Data.Char ( digitToInt, intToDigit )
import Control.Arrow ( first )
newtype BinNum = BinNum { unBinNum :: Integer }
deriving ( Eq, Ord, Num )
main = do
putStrLn "Enter 5 binary numbers [,,] :"
input <- getLine
let ns = read input :: [BinNum]
result = map unBinNum ns
putStrLn $ show result
isBinDigit :: Char -> Bool
isBinDigit c = c >= '0' && c <= '1'
readBinNum :: ReadS BinNum
readBinNum = map (first BinNum) . readInt 2 isBinDigit digitToInt
showBinNum :: BinNum -> ShowS
showBinNum = showIntAtBase 2 intToDigit . unBinNum
instance Read BinNum where
readsPrec _ = readBinNum
instance Show BinNum where
showsPrec _ = showBinNum
Upvotes: 0
Reputation: 47072
You're asking for the input to be converted into an [Int]
using read
, so it's being converted using the same rules as Haskell source code, which means they're being parsed as decimal numbers.
As you want to parse them as binary numbers, you will have to write your own String -> Int
(or, to allow for errors, String -> Maybe Int
) function to convert them into Int
s from binary.
There is no distinction between decimal numbers and binary numbers. There are only numbers. Decimal or binary are artifacts of how numbers are represented as strings.
Upvotes: 2