1
votes

I'm trying to figure out how tuples work in Haskell, and how you can get certain data values from tuples.

I have the following code, and this runs properly, and prints out the tuple output I expect:

test :: Integer -> (Integer, Integer)
test c =  function(1, c)

However, when I try to get just the first value from the tuple, as shown below,

test :: Integer -> Integer
test c = fst function(1, c)

I get the following error

  • Couldn't match expected type '((Integer, Integer) -> Integer, b0)' with actual type '(Integer, Integer) -> (Integer, Integer)'

Any help or advice would be appreciated. Thanks in advance.

1
Test cannot be a name of a function. Function names start with a lowercase letter. - n. 1.8e9-where's-my-share m.
Oh, sorry, I was using lowercase functions, I just changed it to "Test" for examples sake. - Gina Pudra

1 Answers

3
votes

You simply got the syntax wrong.

f x means "apply (call) function f to argument x".

Similarly, f x y means "apply function f to arguments x and y".

Your example function(1, c) means "apply function function to argument (1, c)". Don't let the absence of a space before the opening paren fool you: (1, c) does not mean "call function with two arguments" (as it would in, say, C or Java), it means "make a pair with two components, 1 and c". This pair is then used as a single argument for function.

Now, the next expression, fst function (1, c) means "apply function fst to two arguments - function and (1, c)". This is obviously not what you meant. Instead, you meant to first call function with argument (1, c), and then pass the result as argument to fst. To express this, you may use parentheses:

test c = fst (function (1, c))

But of course this is now too many parentheses. To avoid the extra pair, you may use the ubiquitous operator $:

test c = fst $ function (1, c)

This operator doesn't really do anything interesting, it just applies the function on the left to the argument on the right:

f $ x = f x

The value of this operator is that it makes it possible for the function application to not have the highest precedence, and thus get rid of extra parentheses.