Haskell 有像 Python 和 Ruby 这样的 splat 运算符吗? [英] Does Haskell have a splat operator like Python and Ruby?

查看:23
本文介绍了Haskell 有像 Python 和 Ruby 这样的 splat 运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 和 Ruby 中(我敢肯定,还有其他的).您可以使用 * ("splat") 作为可枚举的前缀,以将其用作参数列表.例如,在 Python 中:

In Python and Ruby (and others as well, I'm sure). you can prefix an enumerable with * ("splat") to use it as an argument list. For instance, in Python:

>>> def foo(a,b): return a + b
>>> foo(1,2)
3
>>> tup = (1,2)
>>> foo(*tup)
3

Haskell 中有类似的东西吗?我认为由于它们的任意长度,它不适用于列表,但我觉得使用元组它应该可以工作.这是我想要的示例:

Is there something similar in Haskell? I assume it wouldn't work on lists due to their arbitrary length, but I feel that with tuples it ought to work. Here's an example of what I'd like:

ghci> let f a b = a + b
ghci> :t f
f :: Num a => a -> a -> a
ghci> f 1 2
3
ghci> let tuple = (1,2)

我正在寻找一个允许我这样做的运算符(或函数):

I'm looking for an operator (or function) that allows me to do:

ghci> f `op` tuple
3

我见过 (<*>) 被称为splat",但它似乎与其他语言中的 splat 指的不是同一个东西.反正我试过了:

I have seen (<*>) being called "splat", but it doesn't seem to be referring to the same thing as splat in other languages. I tried it anyway:

ghci> import Control.Applicative
ghci> f <*> tuple

<interactive>:1:7:
    Couldn't match expected type `b0 -> b0'
                with actual type `(Integer, Integer)'
    In the second argument of `(<*>)', namely `tuple'
    In the expression: f <*> tuple
    In an equation for `it': it = f <*> tuple

推荐答案

是的,您可以将函数应用于元组,使用 元组包.特别是查看 uncurryN 函数,最多可处理 32 个元组:

Yes, you can apply functions to tuples, using the tuple package. Check out, in particular, the uncurryN function, which handles up to 32-tuples:

Prelude Data.Tuple.Curry> (+) `uncurryN` (1, 2)
3

这篇关于Haskell 有像 Python 和 Ruby 这样的 splat 运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆