Skip to content

Instantly share code, notes, and snippets.

@laughedelic
Created November 15, 2011 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laughedelic/1368245 to your computer and use it in GitHub Desktop.
Save laughedelic/1368245 to your computer and use it in GitHub Desktop.
printf с помощью Template Haskell
{-# 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