Tôi muốn gọi hàm printf của Text.Printf bằng mảng nhưng tôi không thể tìm được cách. Dưới đây là hai phiên bản không hoạt động (thực sự giống như ý tưởng).Đối số printf Haskell dưới dạng mảng
lỗiimport Text.Printf
printfa :: (PrintfArg a) => String -> [a] -> String
printfa format args = step (printf format) args
where
step :: (PrintfType r, PrintfArg a) => r -> [a] -> r
step res (x:[]) = res x
step res (x:xs) = step (res x) xs
printfa' :: (PrintfArg a) => String -> [a] -> String
printfa' format args = foldr (\arg p -> p arg) (printf format) args
main = putStrLn $ printfa "%s %s" ["Hello", "World"]
GHC là:
printfa.hs:8:23:
Couldn't match type `r' with `a1 -> r'
`r' is a rigid type variable bound by
the type signature for
step :: (PrintfType r, PrintfArg a1) => r -> [a1] -> r
at printfa.hs:8:5
The function `res' is applied to one argument,
but its type `r' has none
In the expression: res x
In an equation for `step': step res (x : []) = res x
printfa.hs:12:41:
The function `p' is applied to one argument,
but its type `String' has none
In the expression: p arg
In the first argument of `foldr', namely `(\ arg p -> p arg)'
In the expression: foldr (\ arg p -> p arg) (printf format) args
(Tại sao:. Tôi đang viết DSL và muốn cung cấp chức năng printf)
Chỉ cần cung cấp thông tin, có một vực thẳm của sự khác biệt giữa một danh sách liên kết (mà '[a]' là) và mảng. –
Bạn có thực sự muốn ép buộc tất cả các đối số cho printf có cùng loại không? – augustss
Không, tất cả đối số là trường hợp của PrintfArg và không có cùng loại. –