Multiple Return Values in Haskell

Haskell has built-in support for multiple return values through tuples. This feature is often used in idiomatic Haskell, for example to return both result and error values from a function.

import System.IO (print)

-- The (Int, Int) in this function signature shows that
-- the function returns a tuple of 2 Ints.
vals :: (Int, Int)
vals = (3, 7)

main :: IO ()
main = do
    -- Here we use pattern matching to destructure the tuple
    -- returned by vals into two separate values.
    let (a, b) = vals
    print a
    print b

    -- If you only want a subset of the returned values,
    -- use the wildcard pattern '_'.
    let (_, c) = vals
    print c

To run the program, save it as multiple-return-values.hs and use runhaskell:

$ runhaskell multiple-return-values.hs
3
7
7

In Haskell, tuples are used to return multiple values from a function. Pattern matching is used to destructure these tuples and assign values to variables. The wildcard pattern _ is used to ignore values you don’t need, similar to the blank identifier in other languages.

Accepting a variable number of arguments is another feature available in Haskell; we’ll look at this concept next.