I would like to know how to compare two function 开发者_StackOverflow中文版F(x)
& G(x)
in SML, which two functions must return the same value that f(x)==g(x)
, where 1<= x <= 100
.
For example:
- fun f x = x*x;
val f = fn : int -> int
- fun g x = x+x;
val g = fn : int -> int
- iden f g;
val it = false : bool
- fun f x = x*x;
val f = fn : int -> int
- fun g x = if x<0 then 0 else x*x;
val g = fn : int -> int
- iden f g;
val it = true : bool
Since testing whether or not two functions (programs) are equal for all inputs is not computable, your iden
function will likely have to take more parameters than just the two functions that its comparing.
In general, your iden
will be:
- fun iden f g elem = f(elem) = g(elem)
val iden = fn : ('a -> ''b) -> ('a -> ''b) -> 'a -> bool
In your specific case, you would probably want to do something like this:
- fun iden f g = let
= fun iden_h f g (a, b) =
= if a > b then iden_h f g (b, a)
= else if a = b then f(a) = g(a)
= else f(a) = g(a) andalso iden_h f g (a+1, b)
= in
= iden_h f g (1, 100)
= end
val iden = fn : (int -> ''a) -> (int -> ''a) -> bool
-
- iden (fn x => x + x) (fn x => 2 * x);
val it = true : bool
- iden (fn x => x + x) (fn x => x * x);
val it = false : bool
精彩评论