Home > Net >  Haskell function to replace variable in a string with its values. Like f-string (Python) or glue (R)
Haskell function to replace variable in a string with its values. Like f-string (Python) or glue (R)

Time:08-29

I want to replace replace in-place variable in string without using concatenation. I want some function

foo :: String -> [a] -> String

For example

values = [1, 2]      
foo "This is a {?} and this is test3 - {?}" values

Expected Output:

"This is a 1 and this is test3 - 2"

CodePudding user response:

import Data.List.Split (splitOn)
import Data.List ( transpose )

values :: [Integer]
values = [1, 2]     
 
foo :: Show a => [Char] -> [a] -> [Char]
foo xs vs = (concat . concat . transpose) [splitOn "{?}" xs, map show vs]

result :: [Char]
result = foo "This is a {?} and this is test3 - {?}" values

-- "This is a 1 and this is test3 - 2"

Note: "map show" converts the Integer type of values to strings. "concat . concat" flattens the two level nested list. "transpose" is working like zip here. Zip makes tuples instead of lists, so it doesn't flatten directly with "concat".

  • Related