簡體   English   中英

字符串替換運算符,包含Haskell中的列表

[英]String substitution operators with lists in 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

好開始! mergeList非常干凈。

mergeList :: [a] -> [a] -> [a]
mergeList [] ys = ys
mergeList (x:xs) ys = x:mergeList ys xs



listConcat :: [String] -> String
listConcat [] = []
listConcat (x:xs)
  | null xs   = x
  | otherwise = x ++ listConcat xs

你可以為listConcat 特別是,您目前使用兩個基本案例進行遞歸,但您只需要一個。 此外,您可以將類型簽名更改為listConcat :: [[a]] -> [a]以使其更通用。 一旦你清理了你的版本:標准庫中就有這樣的功能。 你能找到嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM