Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does pattern matching not cover list heads in Haskell? [duplicate]

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?

like image 623
Robert Avatar asked Feb 04 '26 01:02

Robert


2 Answers

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.

like image 176
ДМИТРИЙ МАЛИКОВ Avatar answered Feb 05 '26 19:02

ДМИТРИЙ МАЛИКОВ


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.

like image 25
Don Stewart Avatar answered Feb 05 '26 18:02

Don Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!