Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created February 19, 2014 03:24
Show Gist options
  • Select an option

  • Save pasberth/9085513 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/9085513 to your computer and use it in GitHub Desktop.
可変長引数つきの printf
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
format :: String -> String -> String
format [] _ = []
format ('%':'%':s) x = '%' : '%' : format s x
format ('%':'s':s) x = escape x ++ s
format (x:xs) y = x : format xs y
escape :: String -> String
escape [] = []
escape ('%':s) = '%' : '%' : escape s
escape (x:xs) = x : escape xs
unescape :: String -> String
unescape [] = []
unescape ('%':'%':s) = '%' : s
unescape (x:xs) = x : unescape xs
class Printf a where
printf :: String -> a
instance Printf (IO ()) where
printf = putStrLn . unescape
-- sprintf
instance Printf String where
printf = unescape
instance Printf a => Printf (String -> a) where
printf fmt x = printf (format fmt x)
main :: IO ()
main = do
printf "hello world" :: IO ()
printf "hello, %s" "myuon" :: IO ()
printf "%s,%s%%s,%s" "a" "b" "c" :: IO ()
printf "testing a escape %%s" :: IO ()
let { x :: String
; x = printf "hello, %s" "myuon"
} in print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment