Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

functional programming - Feed elements of a tuple to a function as arguments in Haskell?

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
") [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
") [(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
") [(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
" a b) [(1,100),(2,350),(3,600),(4,200)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...