15

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

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

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

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)

我正在寻找允许我执行以下操作的运算符(或函数):

ghci> f `op` tuple
3

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

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
4

3 回答 3

15

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
于 2011-08-14T01:39:48.753 回答
3

The uncurry function turns a function on two arguments into a function on a tuple. Lists would not work in general because of their requirement for homogeneity.

于 2011-08-14T01:15:55.590 回答
3

No, Haskell's type system doesn't like that. Check this similar question for more details:

How do I define Lisp’s apply in Haskell?

BTW, the splat operator you talk about is also known as the apply function, commonly found on dynamical functional languages (like LISP and Javascript).

于 2011-08-14T01:32:12.587 回答