Search code examples
functionhaskellsyntaxdefinitionguard-clause

What is the syntax for different recursions depending on two boolean guards?


I'm very new to Haskell and am trying to write a simple function that will take an array of integers as input, then return either the product of all the elements or the average, depending on whether the array is of odd or even length, respectively.

I understand how to set a base case for recursion, and how to set up boolean guards for different cases, but I don't understand how to do these in concert.

arrayFunc :: [Integer] -> Integer                                                                                       
arrayFunc [] = 1                                                                                                        
arrayFunc array                                                                                                           
| (length array) % 2 == 1 = arrayFunc (x:xs) = x * arrayFunc xs                                                     
| (length array) % 2 == 0 = ((arrayFunc (x:xs) = x + arrayFunc xs) - 1) `div` length xs 

Currently I'm getting an error

"parse error on input '='
Perhaps you need a 'let' in a 'do' block?"

But I don't understand how I would use a let here.


Solution

  • Define an auxiliary inner function like that:

    arrayFunc :: [Integer] -> Integer
    arrayFunc [] = 1
    arrayFunc array
      | (length array) % 2 == 1  =  go1 array
      | (length array) % 2 == 0  =  go2 array
      where
        go1 (x:xs)  =  x * go1 xs
        go2 (x:xs)  =  ((x + go2 xs) - 1) `div` length xs 
    

    This deals only with the syntactical issues in your question. In particular, [Integer] is not an array -- it is a list of integers.

    But of course the name of a variable doesn't influence a code's correctness.