zemmsoares
zemmsoares

Reputation: 353

Change value based on var

I'm trying to read a type of input from a file (Integer, Char...), and let the value depending on the type file.

My problem is if my input is an Integer i have to let value = read contents::Int if my input is Char let value = read contents::String the way im dealing with this is using two different files, i've tried to implement several if clauses but nothing worked so far. whats the best way i can do to approach this?

import System.Environment
import System.IO
import Data.List
import Data.Typeable

---------------------------
{ HASKELL CODE } (problem:)
---------------------------

main :: IO()

main = do
   args <- getArgs
   contents <- readFile (head args)
   let var = (show (typeOf contents))

   if var == "[Char]" then
       let value = read contents::String
   else if var == "[Int]"
       let value = read contents::Int
   else
       putStrLn "test"

   print(problem value)

Upvotes: 0

Views: 84

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153332

One way is to use Either:

parse :: String -> Either Int String
parse s = case readMaybe s of
    Just n -> Left n
    _ -> Right s

doSumthin :: Either Int String -> IO ()
doSumthin (Left 7) = print 50
doSumthin (Right "Santa is real") = putStrLn "Santa is fake"

You could deforest:

parseAndDoSumthin :: String -> IO ()
parseAndDoSumthin s = case (readMaybe s :: Maybe Int, s) of
    (Just 7, _) -> print 50
    (Nothing, "Santa is real") -> putStrLn "Santa is fake"

Upvotes: 2

Related Questions