gpt4 book ai didi

haskell - Haskell 函数什么时候应该采用元组,而不是多个参数?

转载 作者:行者123 更新时间:2023-12-04 14:44:43 25 4
gpt4 key购买 nike

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"

这样做的目的是什么?

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

最佳答案

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

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

grid :: [(Int, Int)]
grid = (,) <$> [1..10] <*> [1..10]

例如,您可能想要添加网格中所有元组的第一个和第二个值(无论出于何种原因),您可以通过在 grid 上映射一个使用元组的函数来实现。 :
addTuple :: (Int, Int) -> Int
addTuple (x, y) = x + y

sumPoints :: [(Int, Int)] -> [Int]
sumPoints = map addTuple

在这种情况下我宁愿使用 uncurry ( :: (a -> b -> c) -> (a, b) -> c ) 使用 +就像平常一样:
sumPoints :: [(Int, Int)] -> [Int]
sumPoints = map (uncurry (+))

这可以说更清晰,也更短;定义高阶类似物也非常容易,例如 uncurry3 , 例如:
> let uncurry3 f (a, b, c) = f a b c
> uncurry3 (\a b c -> a + b + c) (1, 2, 3)
6

关于haskell - Haskell 函数什么时候应该采用元组,而不是多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com