我希望能够使用类似 printf 的功能创建一个字符串,其中的变量从列表中提取并插入到模板字符串中。
即
let templateStr = "First comes %s, then comes %s, after which comes %s"
let vars = ["one","two", "three"]
一些函数返回:
function returns >>> First comes one, then comes two, after which comes three
即在 Python 中我可以做类似的事情:
>>> templateStr = "First comes %s, then comes %s, after which comes %s"
>>> vars = ["one","two", "three"]
>>> outputStr = tempStr % tuple(vars)
>>> print outputStr
First comes one, then comes two, after which comes three
我的尝试
mergeList :: [a] -> [a] -> [a]
mergeList [] ys = ys
mergeList (x:xs) ys = x:mergeList ys xs
-- not actually needed * use: Prelude.concat
listConcat :: [[a]] -> [a]
listConcat [] = []
listConcat (x:xs) = x ++ listConcat xs
-- via @dfeuer list concat is not need because of Prelude.concat
printf' :: String -> [String] -> String
printf' s v = concat $ mergeList (splitOn "%s" s) v
尝试通过@Reid Barton
printf' :: String -> [String] -> String
printf' ('%':'s':rest) (v:vs) = v ++ printf' rest vs
printf' (c:rest) vs = c : printf' rest vs
printf' [] _ = []
两次尝试都给
>>> let templateStr = "First comes %s, then comes %s, after which comes %s"
>>> let vars = ["one","two", "three"]
>>> printf' templateStr vars
"First comes one, then comes two, after which comes three"
最佳答案
另一种更直接的方法概述:
printf' ('%':'s':rest) (v:vs) = ...
printf' (c:rest) vs = ...
... -- handle the remaining cases too
关于Haskell 中带列表的字符串替换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113824/