什么时候Haskell函数应该使用元组而不是多个参数?

fad*_*bee 5 haskell tuples typeclass multimethod

http://www.haskell.org/pipermail/haskell-cafe/2007-August/030096.html中,类型类方法collide被定义为将2元组作为其单个参数,而不是两个"正常"参数(我认为我理解部分应用等).

{-# OPTIONS_GHC -fglasgow-exts
        -fallow-undecidable-instances
        -fallow-overlapping-instances #-}

module Collide where

class Collide a b where
    collide :: (a,b) -> String

data Solid = Solid
data Asteroid = Asteroid
data Planet = Planet
data Jupiter = Jupiter
data Earth = Earth

instance Collide Asteroid Planet where
    collide (Asteroid, Planet) = "an asteroid hit a planet"

instance Collide Asteroid Earth where
    collide (Asteroid, Earth) = "the end of the dinos"

-- Needs overlapping and undecidable instances
instance Collide a b => Collide b a where
    collide (a,b) = collide (b, a)

-- ghci output
*Collide> collide (Asteroid, Earth)
"the end of the dinos"
*Collide> collide (Earth, Asteroid)
"the end of the dinos"
Run Code Online (Sandbox Code Playgroud)

这样做的目的是什么?

什么时候使用元组参数而不是多个参数更好?

Ben*_*ach 5

我几乎从不编写将元组作为参数的函数。如果出现变量固有连接的情况(如 bheklilr 在评论中提到的那样),我更有可能将其打包到它自己的单独数据类型和模式匹配中。

您可能想要定义一个将元组作为参数的函数的一种常见情况是,当您有一个动态Functor生成的元组列表(或任何任意),但想要使用某个函数对其进行映射时,例如

grid :: [(Int, Int)]
grid = (,) <$> [1..10] <*> [1..10]
Run Code Online (Sandbox Code Playgroud)

例如,您可能想要添加网格中所有元组的第一个和第二个值(无论出于何种原因),您可以通过将消耗元组的函数映射到 来实现grid

addTuple :: (Int, Int) -> Int
addTuple (x, y) = x + y

sumPoints :: [(Int, Int)] -> [Int]
sumPoints = map addTuple
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我宁愿做的只是使用uncurry( :: (a -> b -> c) -> (a, b) -> c) 来像平常一样使用+

sumPoints :: [(Int, Int)] -> [Int]
sumPoints = map (uncurry (+))
Run Code Online (Sandbox Code Playgroud)

这可以说更清晰,而且肯定更短;定义高阶类似物也非常容易uncurry3,例如:

> let uncurry3 f (a, b, c) = f a b c
> uncurry3 (\a b c -> a + b + c) (1, 2, 3)
6
Run Code Online (Sandbox Code Playgroud)