I am trying to translate to Idris an example from the Cayenne - a language with dependent types paper.
Here is what I have so far:
PrintfType : (List Char) -> Type
PrintfType Nil = String
PrintfType ('%' :: 'd' :: cs) = Int -> PrintfType cs
PrintfType ('%' :: 's' :: cs) = String -> PrintfType cs
PrintfType ('%' :: _ :: cs) = PrintfType cs
PrintfType ( _ :: cs) = PrintfType cs
printf : (fmt: List Char) -> PrintfType fmt
printf fmt = rec fmt "" where
rec : (f: List Char) -> String -> PrintfType f
rec Nil acc = acc
rec ('%' :: 'd' :: cs) acc = \i => rec cs (acc ++ (show i))
rec ('%' :: 's' :: cs) acc = \s => rec cs (acc ++ s)
rec ('%' :: _ :: cs) acc = rec cs acc -- this is line 49
rec ( c :: cs) acc = rec cs (acc ++ (pack [c]))
I am using List Char
instead of String
for the format argument in order to facilitate with pattern matching as I quickly ran into complexity with pattern matching on String
.
Unfortunately I get an error message I am not able to make sense of:
Type checking ./sprintf.idr
sprintf.idr:49:Can't unify PrintfType (Prelude.List.:: '%' (Prelude.List.:: t cs)) with PrintfType cs
Specifically:
Can't convert PrintfType (Prelude.List.:: '%' (Prelude.List.:: t cs)) with PrintfType cs
If I comment out all the pattern match cases with 3 elements (the ones with '%' :: ...
) in PrintfType
and printf
, then the code compiles (but obviously doesn't do anything interesting).
How do I fix my code so that printf "the %s is %d" "answer" 42
works?