Tuesday, 12 February 2013

Exercise 196: Develop a-function=.



Exercise 196: Develop a-function=. The function determines whether two functions from numbers to numbers produce the same results for 1.23, and -5.775.
Can we hope to define function=?, which determines whether two functions from numbers to numbers are equal?
Answer


; returns true if the functions supplied return the same value for 3
; different numbers
; Function, Function -> Booleas
(define (a-function= x y)
  (and (a-helper x y 1.2) (a-helper x y 3) (a-helper x y -5.775)))
   

; tests if the two functions supplied return the same number
; Function, Function, Number -> Boolean
(define (a-helper x y number)
  (= (x number) (y number)))



; some test functions - both 1 and 3 should return the same value, 2 should not.
(define (test1 x) (* 2 x))
(define (test2 x) (* 3 x))
(define (test3 x) (+ x x))

; and some tests
(check-expect (a-function= test1 test2) false)
(check-expect (a-function= test1 test3) true)



Can we hope to define function=?, which determines whether two functions from numbers to numbers are equal?

We cannot (depending on how you define 'equal functions'). We can check to see the return value of the functions are equal for a specified set of arguments, but without the code introspection offered by languages such as Ruby, you can't see what is inside these black box functions.  

Tuesday, 5 February 2013

Exercise 195: Argue why the following sentences are now legal definitions


Exercise 195: Argue why the following sentences are now legal definitions:
  1. (define (f x) (x 10))
  2. (define (f x) (x f))
  3. (define (f x y) (x 'a y 'b))
Explain your reasoning.

1)  (define (f x) (x 10))
We are now allowed to:
  1. include the names of functions and primitive operations in the definition. 
  2. use variables and function parameters in the first position in a definition
In this case the parameter x is a function that will have the value 10 applied to it.  As we can include functions in a function definition this is legal.

2) (define (f x) (x f))
In this case, both x and f are functions. This function will call the function x passing in the value of itself (ie f). As we can include functions in function definitions, this is now legal.

3) (define (f x y) (x 'a y 'b))
In this case f and x are functions, and y is a value (that could potentially be a function!). The function x will be called, with the values 'a, y and 'b being passed into it. At this point y could either be a value, or a function and provided that the function x is expected the actual item in, this code is legal.