Haskell 中带列表的字符串替换运算符

标签 string haskell

我希望能够使用类似 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/

相关文章:

haskell - 在使用类型系列限制 GADT 时摆脱 "non-exhaustive patten matches"警告

haskell - 如何为 Church 编码的免费 monad 编写解包器?(Haskell)

java - 替换字符串中的相应字符(java)

c - 用 '%20' 替换字符串中的所有空格。假设字符串在字符串末尾有足够的空间来容纳额外的字符

c - 我想过滤数字流以获取某个范围内的值

c++ - 为 haskell 堆栈项目编写静态 cpp 库

haskell - 在 2 维中喜结连理(原为 : tying the knot with a comonad)

python - 如何匹配字符串中的第一个单词?

string - 使用 slice 值的 Golang 字符串格式

sql - 使用 Esqueleto 处理列表类型