我需要连接两个IO String符合S -之间英寸 这就是我提出的,有效的方法 - 什么是正确的方法?
import System.Environment
f :: String -> String -> IO String
f x y = (foldl1 (++)) <$> sequence [(getEnv x),(return "-"),(getEnv y)]
Run Code Online (Sandbox Code Playgroud)
你可以在这里使用一个应用风格的功能:
f :: String -> String -> IO String
f x y = withHyp <$> getEnv x <*> getEnv y
where withHyp ex ey = ex ++ '-' : eyRun Code Online (Sandbox Code Playgroud)
所以在这里我们加入两个Strings,然后通过withHyp函数在中间加入一个hypen .
或者,对于我们需要获取的环境变量列表,我们可以使用mapM并执行intercalate:
import Data.List(intercalate)
f :: [String] -> IO String
f xs = intercalate "-" <$> mapM getEnv xsRun Code Online (Sandbox Code Playgroud)
老实说,你的方法背后的想法实际上看起来非常合理.首先,我可能会使用concatintsead foldl1 (++),并删除一些parens,让我们:
f x y = concat <$> sequence [getEnv x, return "-", getEnv y]
Run Code Online (Sandbox Code Playgroud)
这对我来说真的不怎么样.但是,如果我真的想进一步推动,我会有一些想法.首先,我记得这个intercalate功能.
f x y = intercalate "-" <$> sequence [getEnv x, getEnv y]
Run Code Online (Sandbox Code Playgroud)
将函数应用于列表的每个元素也有一个方便的简写; mapM f = sequence . map f.所以:
f x y = intercalate "-" <$> mapM getEnv [x,y]
Run Code Online (Sandbox Code Playgroud)
我会在那里停下来; 它对我来说看起来很干净和易于维护.