问题描述
在Python和Ruby(以及其他人,我敢肯定)。你可以用 *
(splat)作为参数列表的前缀来使用它作为参数列表。例如,在Python中: >>> def foo(a,b):返回a + b
>>> foo(1,2)
3
>>> tup =(1,2)
>>> foo(* tup)
3
Haskell中有类似的东西吗?我认为它不会在列表中工作,因为它们的长度是任意的,但我觉得用元组它应该工作。这里有一个我想要的例子:
ghci>让f a b = a + b
ghci> :t f
f :: Num a => a - > a - > a
ghci> f 1 2
3
ghci>让tuple =(1,2)
我正在寻找一个操作符(或函数)我这样做:
ghci> f`op` tuple
3
我曾见过(< ; *>)
被称为splat,但它似乎并不指向与其他语言中的splat相同的内容。我试过了:
ghci> import Control.Applicative
ghci> f *元组
< interactive>:1:7:
无法匹配预期的类型`b0 - > b0'
,其实际类型为'(Integer,Integer)'
在'(*)'的第二个参数中,即元组'
在表达式中:f< * GT;元组
在it的等式中:it = f *元组
是的,您可以将函数应用于元组, 包。详细查看函数,可处理多达32个元组:
Prelude Data.Tuple.Curry> (+)`uncurryN`(1,2)
3
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
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
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
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运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!