Hacker News new | ask | show | jobs
by enobayram 2504 days ago
here's ho I'd write it:

    getSocketAPIPort :: Int -> IO Int
    getSocketAPIPort defaultPort = readWithDefault <$> lookupEnv "socketPort"
      where 
        readWithDefault mbPort = fromMaybe defaultPort $ readMaybe =<< mbPort
1 comments

Though I should add that it's in general against the Haskell spirit to write code against needlessly specific types and to combine unrelated functionality. So, I'd first look for a function or write one myself in some utils module that looks up and parses a value from an environment variable:

    readEnv :: Read a => String -> IO (Maybe a)
    readEnv var = (readMaybe =<<) <$> lookupEnv var
Then the function in question becomes much easier (and probably unnnecessary too):

    getSocketAPIPort defaultPort = fromMaybe defaultPort <$> readEnv "socketPort"