在 Haskell 中将元组的元素作为参数提供给函数?
在我的 Haskell 程序中,我想使用 printf 来格式化元组列表。我可以将 printf 映射到一个列表上,一次打印一个值,如下所示:
mapM_ (printf "Value: %d\n") [1,2,3,4]
Value: 1
Value: 2
Value: 3
Value: 4
我希望能够执行如下操作:
mapM_ (printf "Values: %d %d\n") [(1,100),(2,350),(3,600),(4,200)]
Values: 1 100
Values: 2 350
Values: 3 600
Values: 4 200
但这将一个元组传递给 printf,而不是两个单独的值。如何将元组转换为 printf 的两个参数?
In my Haskell program, I want to use printf to format a list of tuples. I can map printf over a list to print out the values one at a time like this:
mapM_ (printf "Value: %d\n") [1,2,3,4]
Value: 1
Value: 2
Value: 3
Value: 4
I want to be able to do something like this:
mapM_ (printf "Values: %d %d\n") [(1,100),(2,350),(3,600),(4,200)]
Values: 1 100
Values: 2 350
Values: 3 600
Values: 4 200
But this passes a tuple to printf, not two separate values. How can I turn the tuple into two arguments for printf?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数
uncurry
将双参数(柯里化)函数转换为对函数。这是它的类型签名:您需要在
printf
上使用它,如下所示:另一种解决方案是使用模式匹配来解构元组,如下所示:
Function
uncurry
converts a two-argument (curried) function into a function on pairs. Here's its type signature:You need to use it on
printf
, like this:Another solution is to use pattern matching to deconstruct the tuple, like this:
Text.Printf
的类型安全替代方案是 formatting 包。 Text.Printf.printf 不确保在编译时格式化参数的数量与参数的数量及其类型一致。请阅读 Chris Done 的文章 Printf 有什么问题? 作为示例。用法示例:
它需要 GHC 扩展 OverloadedStrings 才能正常运行。
而
formatToString ("Value: " % int % " " % int)
的类型为Int ->整数-> String
,取消柯里化后得到类型(Int, Int) ->输入类型与列表中的元素匹配的字符串
。重写过程可以分解;假设
f
=formatString("Value: " ...)
,即首先对f进行咖喱化,实现接受元组的函数,然后执行常规的< a href="https://wiki.haskell.org/Eta_conversion" rel="nofollow">Eta 转换 自
\(x,y) -> uncurry f (x,y)
等价于简单的uncurry f
。要打印结果中的每一行,请使用mapM_
:如果您运行 hlint YourFile.hs,将向您推荐这些重写。
A type-safe alternative to
Text.Printf
is the formatting package.Text.Printf.printf
does not ensure at compile-time that the number of formatting parameters aligns with the number of arguments and their types. Read Chris Done's article, What's wrong with printf? for examples.An example usage:
It requires the GHC extension OverloadedStrings to function properly.
While
formatToString ("Value: " % int % " " % int)
has the typeInt -> Int -> String
, uncurrying it gives the type(Int, Int) -> String
of which the input type matches the elements in the list.The rewriting process can be broken down; assuming
f
=formatString ("Value: " ...)
,That is, first you uncurry f to achieve the function that accepts tuples, and then you perform a regular Eta-conversion since
\(x,y) -> uncurry f (x,y)
is equivalent to simplyuncurry f
. To print each line in the result, usemapM_
:If you run hlint YourFile.hs, these rewrites will be recommended to you.