将元组的元素作为Haskell中的参数传递给函数? [英] Feed elements of a tuple to a function as arguments in Haskell?
问题描述
mapM_(printfValue:% d'\
)[1,2,3,4]
值:1
值:2
值:3
值:4
我希望能够做到这样的事情:
mapM_(printf值:%d%d \)[(1,100),(2,350),(3,600),(4,200)]
数值:1 100
数值:2 350
数值:3 600
数值:4 200
但是这将一个元组传递给printf,而不是两个单独的值。
函数 uncurry $ c $>如何将元组转换为printf的两个参数? c>将一个双参数(curried)函数转换成一对函数。这是它的类型签名:
uncurry ::(a - > b - > c) - > (a,b)→> c
您需要在 printf
,像这样:
mapM_(uncurry $ printf值:%d%d \)[(1,100), (2,350),(3,600),(4,200)]
另一个解决方案是使用模式匹配来解构元组,如下所示:
mapM_(\(a,b) - > printf值:%d%d \ nab)[(1,100),(2,350),(3,600),(4,200)]
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?
Function uncurry
converts a two-argument (curried) function into a function on pairs. Here's its type signature:
uncurry :: (a -> b -> c) -> (a, b) -> c
You need to use it on printf
, like this:
mapM_ (uncurry $ printf "Values: %d %d\n") [(1,100),(2,350),(3,600),(4,200)]
Another solution is to use pattern matching to deconstruct the tuple, like this:
mapM_ (\(a,b) -> printf "Values: %d %d\n" a b) [(1,100),(2,350),(3,600),(4,200)]
这篇关于将元组的元素作为Haskell中的参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!