Created
February 19, 2014 03:24
-
-
Save pasberth/9085513 to your computer and use it in GitHub Desktop.
可変長引数つきの printf
This file contains hidden or 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 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