A
A
Alexander Myasnikov2014-08-08 00:19:52
Haskell
Alexander Myasnikov, 2014-08-08 00:19:52

How to use pattern matching in guard expressions in Haskell (in a specific example)?

Goodnight. Tell me how to use pattern matching in guard expressions.
For example, there is a working code:

isPalindrome'' :: Eq a => [a] -> Bool
isPalindrome'' [] = True
isPalindrome'' [x] = True
isPalindrome'' list
    | head list == last list = (isPalindrome' . tail . init) list
    | otherwise = False

I'm trying to convert the code to:
isPalindrome''' :: Eq a => [a] -> Bool
isPalindrome''' list
    | [] = True
    | [x] = True
    | head list == last list = (isPalindrome' . tail . init) list
    | otherwise = False

The interpreter writes that 'x' is not defined. How it is possible to correct it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ruchkin, 2014-08-14
@amyasnikov

Pattern matching can be used, but guards must explicitly indicate what is being matched, i.e. in this case, the argument is list

foo :: Eq a ⇒ [a] → Bool
foo list
  | [] ← list = True
  | [x] ← list = True
  | head list ≡ last list = foo . tail . init $ list
  | otherwise = False

Although I personally prefer the original version.

S
Sergey, 2014-08-08
@begemot_sun

In the first example, you have defined a function and you are pattern matching the argument.
In the second case, you defined a function with a list argument, and for some reason you think that the
compiler will accept [x] as an argument, nothing like that. In guard expressions, you should write already defined identifiers

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question