I just started learning functional programming (using Scheme language). I read that a higher order function is the function which either takes in another function as argument or returns another function or both. So I am trying to convert the below code to a higher order function:
;; define two procedures - one for calculating square & one for finding double of a number
(define (square x) (* x x ))
(define (double x) (+ x x ))
(square 5)
=> 25
(double 5)
=> 10
Now I came up with the below one:
;; Implementation 2:
(define (applyToItself f x) (f x x ) )
(define (square x) (applyToItself * x ))
(define (double x) (applyToItself + x ))
(square 5)
=> 25
(double 5)
=> 10
I created a function applyToItself which takes a function and a value and returns the computed value by applying the incoming function on the incoming value.
Now the square and double function just uses applyToItself with * and +.
Finally I came across another way of this implementation:
;;Implementation 3:
(define (applyToItself f) (lambda(x) (f x x )) )
(define square (applyToItself * ))
(define double (applyToItself + ))
(square 5)
=> 25
(double 5)
=> 10
This applyToItself implementation now takes in just a function and returns another function rather than the computed value.
My questions are:
- is there any significant difference or pros and cons between Implementation 2 and implementation 3?
- is
applyToItselfin Implementation 2 and implementation 3 both higher order functions? - which one is correct or better implementation?