Created
November 15, 2011 20:33
-
-
Save laughedelic/1368245 to your computer and use it in GitHub Desktop.
printf с помощью Template Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell #-} | |
module Printf (printf) where | |
-- Импортируем инструментарий Template Haskell | |
import Language.Haskell.TH | |
-- | Шаблон для функции printf | |
-- Пример использования: | |
-- > putStrLn ( $(printf "Number %d is %s of %d.") 327 "square" (327^2) ) | |
printf :: String -- ^ строка форматирования | |
-> ExpQ | |
printf = pr [|""|] | |
-- Вспомогательный шаблон | |
pr :: ExpQ -- ^ аккумулятор с уже сгенерированным кодом правой части лямбды | |
-> String -- ^ необработанный ещё остаток строки | |
-> ExpQ -- ^ результат – сгенерированный код лямбда-выражения | |
pr acc "" = acc | |
pr acc str = | |
let (plain, format) = break (=='%') str | |
in case format of | |
('%':'s':rest) -> [| \x -> $(pr [| $acc ++ plain ++ x |] rest) |] | |
('%':'d':rest) -> [| \x -> $(pr [| $acc ++ plain ++ show x |] rest) |] | |
('%' :rest) -> pr [| $acc ++ plain ++ "%" |] rest | |
_ -> [| $acc ++ str |] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment