user3373360
user3373360

Reputation: 93

How to replace empty slots in a Template with strings in Haskell?

I'm trying to write a function which takes a Template "xs" and replaces the empty slots with the strings in "strs". Below is an example:

template {}word{}{} ["9", "2", "7"] = 9word27

I'm looking for any help that may be useful. Below is what I have so far:

template :: Template -> [String] -> String
template (Template xs) strs =

Some helper functions:

data Slot = Slot
          deriving (Show, Eq)

data Template =
  Template [Either String Slot]
  deriving Eq

instance Show Template where
  show (Template xs) =   concat $ map f xs
    where f (Left x) = x
          f (Right x) = "{}"
data Def =
  Def [Template]
  deriving Eq

We can always assume that the number of slots is equivalent to the number of strings.

Upvotes: 0

Views: 208

Answers (1)

user2407038
user2407038

Reputation: 14598

A very simple solution using the State monad is possible:

import Control.Monad
import Control.Monad.State 

template :: Template -> [String] -> String
template (Template xs) strs = evalState (foldM f [] xs) strs where 
  f s (Left s') = return (s ++ s')
  f s Right{} = state $ \(r:rs) -> (s++r,rs) 

As per your requirements, this crashes (with a pattern match error) in case the number of slots and strings differ.

Upvotes: 1

Related Questions