2015-09-23 39 views
0

我想寫一個函數,它需要一個模板「xs」,並用「strs」中的字符串替換空的插槽。下面是一個示例:如何用Haskell中的字符串替換模板中的空插槽?

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

我正在尋找任何可能有用的幫助。下面是我到目前爲止有:

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

一些輔助功能:

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 

我們總是假設槽的數量相當於弦數。

+2

如果插槽和字符串的數量不同會怎麼樣? – Yuuri

+0

@Yuuri它可以崩潰。對於這種情況,我們只需要擔心插槽的數量是否等於字符串的數量。 – user3373360

回答

1

使用State單子一個非常簡單的解決方案是可能的:

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) 

按您的要求,此崩潰(帶有圖案匹配誤差)的情況下,狹槽和串的數量是不同的。

+0

我收到一個錯誤: 約束中的非類型變量參數:MonadState [[a]] m (使用FlexibleContexts來允許這個) – user3373360

相關問題