When do Haskell functions accept tuples rather than multiple arguments?

In http://www.haskell.org/pipermail/haskell-cafe/2007-August/030096.html, the typeclass method is collidedefined as accepting a 2-tuple as its only argument, and not two "normal" arguments (I think I understand partial application, etc.).

{-# 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"

What is the purpose of this?

When is it better to use a tuple argument rather than multiple arguments?

+4
source share
2 answers

, . , ( 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
+4

, ( ), , . , , 2 , :

add :: Num a => a -> a -> a
add x y = x + y

, - 2-uple 2-D-, . , , , , :

add :: Num a => (a,a) -> (a,a) -> (a,a)
add (x,y) (x,y') = (x+x', y+y')

add :: Num a => a -> a -> a -> a -> (a,a)
add a b c d = (a+c, b+d)

, , , - . :

add :: Num a => ((a,a),(a,a)) -> (a,a)

, collide , ( , , , , 2-uples), , , collide .

+2

Source: https://habr.com/ru/post/1547759/


All Articles