Elon
Elon

Reputation: 13

Can someone help me understand this recursion in Haskell?

Here is the code:

func [] _ = 0
func (head:tail) num
| head > num = func tail num
| head <= num = head + (func tail num)

main = print(func [4,1,2,5,7,6] 2 * 3)

Here is my solution:

4 + func[1,2,5,7,6] 6 
    -> 1 + func[2,5,7,6] 6 
           -> 2 + func[5,7,6] 6 
                  -> 5 + func[7,6] 6 
                         -> func[6] 6
                            -> 6 + func[] 6
 ---> 4 + 1 + 2 + 5 + 6 = 18

But I checked in online compiler solution is 9, where did I make a mistake I don't get it. It is pretty simple code.

Upvotes: 1

Views: 80

Answers (1)

chepner
chepner

Reputation: 530853

The expression providing the argument to print should be understood as

(func [4, 1, 2, 5, 7, 6] 2) * 3

not

func [4, 1, 2, 5, 7, 6] (2 * 3)

because function application takes precedence over any infix operator.

Upvotes: 4

Related Questions