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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With