Home > Enterprise >  What is wrong with this lambda function?
What is wrong with this lambda function?

Time:11-02

I am at the beggining of Get Programming with Haskell and just learned lambda functions. As an exercise I tried to convert the following example to use a lambda.

calcChange owed given =
  if   change > 0
  then change
  else 0
  where change = given - owed

calcChange 9 7 returns 0 and calcChange 7 9 returns 2

Now, here is my attempt

calcChange owed given =
  (\change ->
      if   change > 0
      then change
      else 0
  ) given - owed

which fails: calcChange 7 9 returns 2 but calcChange 9 7 returns -2.

What is wrong with my attempt?

CodePudding user response:

In the first example, change has value given - owned. In the second, simply given. The results of that lambda then have owned subtracted from them.

You likely meant to send given - owned as the argument to that lambda.

calcChange owed given =
  (\change ->
      if   change > 0
      then change
      else 0
  ) (given - owed)

Or, using $:

calcChange owed given =
  (\change ->
      if   change > 0
      then change
      else 0
  ) $ given - owed

CodePudding user response:

The lambda only receives given.

(\change ->
      if  change > 0
      then change
      else 0
) given - owed

==>

(if given > 0 then given else 0) - owed

==> (since given is positive)

given - owed

CodePudding user response:

Operators all have precedence levels between 0 and 9. Function application behaves like an operator with precedence 10, though, so

(\change ->
  if   change > 0
  then change
  else 0
) given - owed

behaves like

((\change ->
  if   change > 0
  then change
  else 0
) given) - owed

not

(\change ->
  if   change > 0
  then change
  else 0
) (given - owed)
  • Related