Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using guards after assigning some variables first

Tags:

syntax

haskell

I know I can do this...

isZero :: Int -> Bool
isZero x
  | x == 0      = True
  | otherwise   = False

But can I do something like this?

isPalindrome :: Int -> Bool
isPalindrome x
  let digitList = intToDigits x -- Decomposes the integer into
                                -- digits, i.e. 37 -> [3, 7]
  | digitList == reverse digitList                = True
  | otherwise                                     = False

This will result in compilation errors, but I'm sure that you know what I'm trying to do.

like image 409
Pieter Avatar asked Dec 03 '22 02:12

Pieter


1 Answers

Use a where clause instead

isPalindrome :: Int -> Bool
isPalindrome x
    | digitList == reverse digitList = True
    | otherwise                      = False
    where digitList = intToDigits x

Of course, for this example we could just skip the guards and write

isPalindrome x = digitList == reverse digitList
    where digitList = intToDigits x
like image 78
hammar Avatar answered Dec 20 '22 00:12

hammar