我如何“打开"包装箱?一个列表作为Haskell中的单个参数? [英] How do I "unpack" a list as individual arguments in Haskell?

查看:50
本文介绍了我如何“打开"包装箱?一个列表作为Haskell中的单个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell中是否有内置或惯用的方式来解压缩"列表中的元素并将其视为函数的单独参数?

Is there builtin or idiomatic way in Haskell to "unpack" the elements of a list and treat them as individual arguments to a function?

例如,如果我有 f :: a->b->c->d->e 是否有类似

For example, if I have f :: a -> b -> c -> d -> e is there something compact like

f (unlist x)

完成

let x = [1,2,3,4] in f (x!!0) (x!!1) (x!!2) (x!!3) 

或至少以一种较少的"shouty"(太多的 !! 重复)方式来解压缩通常已知长度的列表(以便可以用作函数的参数)情况).

or at least a less "shouty" (too many !! repetitions) way to unpack a list of known length in general (so that it can be used as arguments to a function, in this case).

基本上,我要寻找的是类似 Sequence @@ 在Mathematica中所做的事情:

Essentially what I'm looking for is something like what Sequence@@ does in Mathematica:

f[Sequence@@{1, 2, 3, 4}]

推荐答案

在Haskell类型系统中并不是特别有用:

It wouldn't be particularly useful in Haskell type system:

  1. 正如Mephy指出的那样,您需要为每个列表长度使用一个单独的函数,并且在传递错误长度的列表时,它将在运行时失败;
  2. 所有参数都必须具有相同的类型.

鉴于此,使用元组比使用列表更有意义,因为它避免了两个问题.标准库包括 uncurry ,它对2个参数的函数执行此操作,您可以类推地定义 uncurry3 等:

Given this, use of tuples makes more sense than lists, as it avoids both problems; the standard library includes uncurry which does this for functions of 2 arguments, and you could define uncurry3, etc. by analogy:

uncurry3                 :: (a -> b -> c -> d) -> ((a, b, c) -> d)
uncurry3 f (a, b, c)     =  f a b c

这篇关于我如何“打开"包装箱?一个列表作为Haskell中的单个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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