haskell - 使用列表中的项目作为参数

标签 haskell functional-programming

假设我有一个具有以下类型签名的函数:

g :: a -> a -> a -> b

我还有一个 a 列表(我们称之为 xs),我知道它至少包含三个项目。我想将 g 应用于 xs 的前三项。我知道我可以定义一个组合器,如下所示:

($$$) :: (a -> a -> a -> b) -> [a] -> b
f $$$ (x:y:z:_) = f x y z

然后我就可以使用g $$$ xs。这使得 $$$ 有点像 uncurry,但对于具有相同类型的三个参数和列表而不是元组的函数。

有没有办法使用标准组合器来惯用地做到这一点?或者更确切地说,在 Haskell 中执行此操作最惯用的方法是什么?我认为在 $$$ 的非中缀版本上尝试 pointfree 可能会让我知道从哪里开始,但输出是令人厌恶的 10 flip 、一些 headtailap 以及 28 个括号。

(注意:我知道这首先并不是一个非常 Haskelly 要做的事情,但我遇到过一些情况,这似乎是一个合理的解决方案,特别是在使用 Parsec 时。我当然会如果这是最佳答案,请接受“永远不要在真实代码中执行此操作”,但我更希望看到一些涉及 ((->) r) 的巧妙技巧> monad 或其他什么。)

最佳答案

Or rather, what's the most idiomatic way to do this in Haskell?

惯用语?如果您确实想要一个执行 ($$$) 功能的函数,那么您拥有的代码可能与您将得到的一样惯用。

I'd prefer to see some clever trick

哦,好吧,在那种情况下。

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE UndecidableInstances #-}
class ListApply f a r | f -> a r where
    ($...) :: f -> [a] -> r

instance (TypeCast b r) => ListApply b a r where
    x $... _ = typeCast x

instance (ListApply f a r) => ListApply (a -> f) a r where
    f $... (x:xs) = (f x) $... xs

这就是一个完全通用的解决方案:给定一个任意数量的函数,其签名如 a -> a ... -> b,将其应用于列表中尽可能多的元素 [a](根据需要)。演示:

ones :: [Int]
ones = repeat 1

test1 x = x
test2 x y = x + y
test3 x y z = (x + z) * (y + z)

在 GHCi 中:

> test1 $... ones
1
> test2 $... ones
2
> test3 $... ones
4

I'll certainly accept "don't ever do this in real code" if that's the best answer

你可能想这么做。

<小时/>

哦,运行上面的代码需要一些样板:

class TypeCast   a b   | a -> b, b->a   where typeCast   :: a -> b
class TypeCast'  t a b | t a -> b, t b -> a where typeCast'  :: t->a->b
class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t->a->b
instance TypeCast'  () a b => TypeCast a b where typeCast x = typeCast' () x
instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast''
instance TypeCast'' () a a where typeCast'' _ x  = x

这是类型级元编程的瑞士军刀,由 Oleg Kiselyov 提供.

关于haskell - 使用列表中的项目作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2899278/

相关文章:

haskell - 由于标志字节串--lt-0_10_4,无法使用 Stack 构建 hello world 程序

haskell - 为什么 Glasgow Haskell 编译器在这里报告多个类型错误?

functional-programming - 如何查找 ML 字符串列表中出现的次数?

java - RxJava : merge() changes the order of the emitted items?

java - 函数式编程(Streams)返回类型ArrayList java

javascript - Lodash get vs. es6 后备值?

python - 如何使用 map 应用 n 次函数

Haskell 共享库未正确加载

haskell - 如何在堆栈中使用 haste/hplayground

haskell - 如何将字符串解析为 GADT