Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two IOs with - in haskell

Tags:

haskell

monads

I need to join two IO Strings with a - in between. Here's what I came up with, which works - what's the right way?

import System.Environment
f :: String -> String -> IO String
f x y = (foldl1 (++)) <$> sequence [(getEnv x),(return "-"),(getEnv y)]
like image 436
Carbon Avatar asked Dec 03 '22 10:12

Carbon


1 Answers

You could here use an applicative style function:

f :: String -> String -> IO String
f x y = withHyp <$> getEnv x <*> getEnv y
    where withHyp ex ey = ex ++ '-' : ey

So here we join the two Strings that are then joined with a hypen in the middle through the withHyp function.

Or for a list of environment variables that we need to fetch, we can use mapM and perform an intercalate:

import Data.List(intercalate)

f :: [String] -> IO String
f xs = intercalate "-" <$> mapM getEnv xs
like image 78
Willem Van Onsem Avatar answered Dec 30 '22 10:12

Willem Van Onsem