Home > database >  Extracting parameters in Haskell function
Extracting parameters in Haskell function

Time:10-08

I have a function that takes a single character and a list of tuples, and displays one element from the tuple. This is the function:

foo [a] ((x,y):xs) = x

It compiles fine, however, when I try to run

foo 'a' [('b',1),('c',2)]

It gives me this error:

<interactive>:2:5: error:
• Couldn't match expected type ‘[a10]’ with actual typeCharIn the first argument of ‘foo’, namely ‘'a'’
  In the expression: foo 'a' [('b', 1), ('c', 2)]
  In an equation for ‘it’: it = foo 'a' [('b', 1), ('c', 2)]

How do I declare a character "a" in the definition of foo such that foo 'a' [('b',1),('c',2)] does not give me this error?

CodePudding user response:

Figured it out with @Silvo Mayolo 's comment Used just a instead of [a], since I'm trying to match a single character and not a list.

CodePudding user response:

The same way you accepted a single character in the first element of the first tuple in the list; you expected a character there and just wrote a variable name x to bind to the value of that character.

Any time you want to accept any value1 as an argument, just use a variable name; a or x or y or theCharacter, whatever name you like.

If you write a pattern with more structure than that (like [a], or (x, y), or Just a, or ((x,y):xs)) then you're not just accepting any argument value1, you're writing a pattern match that will only work for values that have the same "shape" as your pattern (e.g. [a] matches a list with only one element, ((x,y):xs) matches a list with at least one element whose first element is a tuple of x and y and whose tail is xs, etc).

In your case having used the pattern [a] Haskell has inferred that the type of this parameter must be some sort of list. 'a' is a Char, which is not a list, so this is a type error. However if you did want to pass a list there your pattern would still most likely be wrong. [a] matches a list with one and only one element; empty lists or lists longer than one won't match this pattern, so it only makes sense to use [a] as a pattern when you have other cases that will cover lists with zero or multiple elements. If you just want to accept any list without caring about how many elements you have, you do the same thing as for any other type: just write a variable name.


1 Of the right type. You're still subject to the constraints of the declared or inferred type for the function and its parameters!

  • Related