Haskellでformat

derok
記事: 51
登録日時: 12年前

Haskellでformat

投稿記事 by derok » 9年前

Haskellでformatできるのようなmoduleを作りました。

CODE:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE IncoherentInstances  #-}

module Format(format,formatLn,fillf) where

class Arg a where
	format_ :: String -> a 
	formatLn_ ::String -> a
	
instance Arg (IO ()) where
	format_ acc = putStr acc
	formatLn_ acc = putStrLn$format_ acc

instance Arg String where
	format_ acc = acc
	formatLn_ acc = acc ++ "\n"
	
instance (Show a, Arg r) => Arg (a -> r) where
	format_ acc = \x -> format_ (acc ++ show x)
	formatLn_ acc = \x -> formatLn_ (acc ++ show x)

instance (Arg r) => Arg (String -> r) where
	format_ acc = \x -> format_ (acc ++ x)
	formatLn_ acc = \x -> formatLn_ (acc ++ x)

format :: Arg t => t
format = format_ []

formatLn :: Arg t => t
formatLn = formatLn_ []

fillf::(Show s)=>Char->Int->s->String
fillf c n v = 
	let str = show v
	in replicate (n-length str) c ++ str
ほとんど参考サイトのままですが、show "aaa"が"aaa"になる対策がそこそこ大変だったので公開します。

CODE:

import Format
import Control.Monad
	
main = do
	putStrLn$format 1 "formatLn (fillf ' ' 3 x) "^2:" (x*x)::IO ())	
のようにformat の後に表示させたいものを並べます。
参考サイト
https://github.com/Kinokkory/wiwinwlh-j ... -functions

コメントはまだありません。