1
votes

I want to make a program that

  • takes a character and a list of pairs of characters as arguments,
  • returns the first element of the pair if it is equal to the input character, or returns the unchanged pair otherwise.

I have the following code:

lookUp :: Char -> [(Char, Char)] -> Char    
lookUp a [] = []
lookUp a [(x,y),(xs,ys)]
   | a == x = y : lookUp [(xs,ys)]
   | otherwise = x : y : lookUp [(xs,ys)]

When I compile it, I get a lot of mistakes:

Couldn't match expected type 'char' with actual type [t0]

In an equation for 'lookUp'

and so on...

Sorry, I'm relatively new to Haskell. I'm pretty sure I made a mistake when dealing recursively with the tuple ([(x,y),(xs,ys)]), but I don't know how to change it. Any ideas?

1
I don't quite understand - do you want a list of Chars? Can you say precisely what you want the function to do?user2008934
If you want to return a value and a pair in different cases, you can wrap the result type in Either data type.Sibi
returns the first element of the pair if it is equal to the input character, or returns the unchanged pair otherwise. You can't do that. The type of your result cannot differ from one case (Char) to the other ((Char,Char)). Please clarify your specs.jub0bs

1 Answers

1
votes

This modification of your code will type check:

-- lookUp :: we'll have GHC tell us the type signature    
lookUp a [] = []
lookUp a ((x,y):pairs)
   | a == x = y : lookUp a pairs
   | otherwise = x : y : lookUp a pairs

Some obvious mistakes:

  • When you recursively call lookUp you only called it with one argument (you forgot the a argument)
  • The pattern [(x,y),(xs,ys)] will only match a list of exactly two pairs of characters. The pattern ((x,y):pairs) matches a non-empty list of pairs. The first pair is deconstructed into characters x and y and the remaineder of the list is bound to pairs.

Use the :t command in ghci to have GHC tell you what the type signature is.

Now whether or not this is what you want is another question.