Skip to content

Instantly share code, notes, and snippets.

@Hirrolot
Last active February 23, 2024 12:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hirrolot/b5b23af0dcb68cf7e87e72baf6da6ef6 to your computer and use it in GitHub Desktop.
Save Hirrolot/b5b23af0dcb68cf7e87e72baf6da6ef6 to your computer and use it in GitHub Desktop.
Generic `printf` implementation in Idris2
data Fmt = FArg Fmt | FChar Char Fmt | FEnd
toFmt : (fmt : List Char) -> Fmt
toFmt ('*' :: xs) = FArg (toFmt xs)
toFmt ( x :: xs) = FChar x (toFmt xs)
toFmt [] = FEnd
PrintfType : (fmt : Fmt) -> Type
PrintfType (FArg fmt) = ({ty : Type} -> Show ty => (obj : ty) -> PrintfType fmt)
PrintfType (FChar _ fmt) = PrintfType fmt
PrintfType FEnd = String
printf : (fmt : String) -> PrintfType (toFmt $ unpack fmt)
printf fmt = printfAux (toFmt $ unpack fmt) [] where
printfAux : (fmt : Fmt) -> List Char -> PrintfType fmt
printfAux (FArg fmt) acc = \obj => printfAux fmt (acc ++ unpack (show obj))
printfAux (FChar c fmt) acc = printfAux fmt (acc ++ [c])
printfAux FEnd acc = pack acc
main : IO ()
main = putStrLn $ printf "Mr. John has * contacts in *." 42 "New York"
@Hirrolot
Copy link
Author

This implementation doesn't work on Idris1 due to this strange error: Incomplete term ([__]). However, in Idris2, everything should work smoothly.

@Hirrolot
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment