How to write this Lisp / Scheme code?

A lambda expression that takes a function (of one argument) and a number, and applies the function to twice the number.

+5
source share
3 answers

Application function twice:

(lambda (f x) (f (* 2 x)))

Applying a function to a number two times (this is what you might have intended to ask):

(lambda (f x) (f (f x)))
+8
source

Greg's answer is correct, but you might think about how you can break this problem down to find the answer yourself. Here is one approach:

; A lambda expression
;(lambda () )

; which takes a function (of one argument) and a number
;(lambda (fun num) )

; and applies the function
;(lambda (fun num) (fun num))

; to twice the number
;(lambda (fun num) (fun (* 2 num)))

((lambda (fun num) (fun (* 2 num))) + 12)
+5
source

Here is another way to get closer to it:

Write down the contract, purpose and title:

;; apply-double : function -> number -> any
;; to apply a given function to double a given number
(define (apply-double fun num) ...)

Write some tests:

(= (apply-double identity 10) 20)
(= (apply-double - 15) -30)
(= (apply-double / 7) 1/14)

Define a function:

(define (apply-double fun num) 
  (fun (* 2 num)))

This is the abbreviation for the recipe here: http://www.htdp.org/2003-09-26/Book/

+2
source

All Articles