bevo009
bevo009

Reputation: 523

How to convert this let/where function to a Lambda in Haskell

How exactly do I convert this let/where function to a lambda in Haskell?

Let statement form:

calc x =    let ad5 x = x + 5
                sqr x = x * x
                dbl x = x * 2
            in
                ad5 . sqr . dbl $ x

Where declaration form:

calc x = ad5 . sqr . dbl $ x
  where
        ad5 x = x + 5
        sqr x = x * x
        dbl x = x * 2

Lambda form? Maybe similar to this example from Get Prog, where the variables are declared first, and then defined at the bottom:

sumSqrOrSqrSum4 x y =   (\sumSqr sqrSum ->
                        if sumSqr > sqrSum
                        then sumSqr
                        else sqrSum) (x^2 + y^2) ((x + y)^2)

Upvotes: 4

Views: 766

Answers (2)

bradrn
bradrn

Reputation: 8467

The idea is that this let expression:

let x = y in z

Is exactly the same as this lambda:

(\x -> z) y

Where y is being used as a parameter and hence is bound to x.

In your case, this would result in:

calc x = (\ad5 sqr dbl -> (ad5 . sqr . dbl $ x))
         (\x -> x + 5)
         (\x -> x * x)
         (\x -> x * 2)

Of course, outside of this exercise few people would actually write it this way :)

Upvotes: 6

Robin Zigmond
Robin Zigmond

Reputation: 18249

The most simple and straightforward translation to a lambda would be

calc = \x -> (x*2)*(x*2) + 5

although obviously you could use basic mathematics to simplify that expression a little bit.

Upvotes: 1

Related Questions