Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameters within where clause

Tags:

haskell

Can you please tell me the correct way to write a function within 'where' clause? I struggle to phrase the question so I'd rather show in an example:

I could use the parameters supplied to the top level function in where clause like so

complexMath num1 num2 = sum * sum
  where sum = num1 + num2

or I could parameterize the function within 'where' clause as well like so

 complexMath num1 num2 = (sum num1 num2) * (sum num1 num2)
  where sum n1 n2 = n1 + n2

Both variants work but there should be certain correct way of doing it, at least syntax wise. So what is it? Maybe it does not really matter and I am just being silly...

Thanks.

Edit

I changed the function example to make it a bit clearer so that sum function is used twice.

And what about this one?

complexMath num1 = let num2 = 10 + 8 in sum num2 * sum num2
  where sum n2 = num1 + n2

Would this be the correct way to write it?

like image 356
r.sendecky Avatar asked Sep 15 '26 05:09

r.sendecky


1 Answers

Local Constants

Both are correct syntax, but in a where clause, there's no need to parameterise anything unless it's a recursive call, so your first variant is better:

complexMath num1 num2 = sum + 1000
  where sum = num1 + num2

This non-parameterised where is good for if there's a value that you want to reuse, like

complexMath num1 num2 = sum * (sum + 1000) 
  where sum = num1 + num2

The second one didn't need the brackets because function application has higher precedence

complexMath num1 num2 = sum num1 num2 + 1000
  where sum n1 n2 = n1 + n2

but since the local sum function is only used once, it's unnecessary. In fact, in this example, it's simpler to inline the whole thing as complexMath num1 num2 = num1 + num2 + 1000 but I'm sure this is just an example.

Where you might want to parameterise

If you were using a function for something more interesting:

complexMath num1 num2 = triangle num1 + num2 + 1000
  where  triangle 0 = 0
         triangle n = n + triangle (n-1)

where it gets called multiple times, that's when to parameterise.

Also, if you repeatedly used it:

complexMath num1 num2 = square (square num1 + square num2 + 1000)
  where square x = x * x
like image 111
AndrewC Avatar answered Sep 16 '26 19:09

AndrewC