Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’s pretty simple code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading