3

I want to use the following code/ functionality in Haskell:

test :: String -> String -> Bool
test (x:xs) (x:ys) = True
test _        _    = False

This should check if both lists begin with exactly the same element.
But this does not work.
My compiler says: Conflicting definitions for x

I thought a pattern matching like this had to work in a functional language. I just worked with Prolog before and I'm pretty sure it worked there :/

Is this not implemented in Haskell or is my Syntax wrong?

Robert
  • 1,286
  • 1
  • 17
  • 37
  • A problem with implicit comparison would arise when the list would.contain incomparable items (e.g. functions). Allowing this implicit comparison would (probably) make the syntax less clear. Though there is the strange thing with matching numeral constants, which uses fromIntegral and comparison. – Laar Jul 29 '13 at 20:25

2 Answers2

6

You probably wants something like that.

test :: String -> String -> Bool
test (x:xs) (y:ys) = x == y
test _        _    = False

As @TikhonJelvis noticed, haskell is not a Prolog, so you can't check the equality of the variables inside pattern matching.

3

Pattern matching doesn't unify variables.

test :: String -> String -> Bool
test (x:xs) (y:ys) = x == y
test _        _    = False

So you can test each variable for equality separately, as above.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468