我正在尝试将 Cayenne的一个例子转换为Idris - 一种具有依赖类型的语言 paper。
这是我到目前为止所做的:
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]))
我使用List Char
代替String
作为格式参数,以便于模式匹配,因为我在{{1}上快速遇到模式匹配的复杂性}。
不幸的是,我收到一条错误消息,我无法理解:
String
如果我在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
和'%' :: ...
中注释掉所有带有3个元素(带PrintfType
的元素)的模式匹配案例,那么代码会编译(但显然不会做任何事情)有趣)。
如何修复代码以使printf
有效?
答案 0 :(得分:14)
在定义模式重叠的函数时,似乎idris中有一些current limitations(例如'%' :: 'd'
与c :: cs
重叠。经过多次尝试,我终于想出了一个解决方法这样:
data Format = End | FInt Format | FString Format | FChar Char Format
fromList : List Char -> Format
fromList Nil = End
fromList ('%' :: 'd' :: cs) = FInt (fromList cs)
fromList ('%' :: 's' :: cs) = FString (fromList cs)
fromList (c :: cs) = FChar c (fromList cs)
PrintfType : Format -> Type
PrintfType End = String
PrintfType (FInt rest) = Int -> PrintfType rest
PrintfType (FString rest) = String -> PrintfType rest
PrintfType (FChar c rest) = PrintfType rest
printf : (fmt: String) -> PrintfType (fromList $ unpack fmt)
printf fmt = printFormat (fromList $ unpack fmt) where
printFormat : (fmt: Format) -> PrintfType fmt
printFormat fmt = rec fmt "" where
rec : (f: Format) -> String -> PrintfType f
rec End acc = acc
rec (FInt rest) acc = \i: Int => rec rest (acc ++ (show i))
rec (FString rest) acc = \s: String => rec rest (acc ++ s)
rec (FChar c rest) acc = rec rest (acc ++ (pack [c]))
Format
是表示格式字符串的递归数据类型。 FInt
是一个int占位符,FString
是一个字符串占位符,FChar
是一个char字面值。使用Format
我可以定义PrintfType
并实施printFormat
。从那里,我可以顺利地扩展到一个字符串,而不是List Char
或Format
值。最终结果是:
*sprintf> printf "the %s is %d" "answer" 42
"the answer is 42" : String