ML; composite function n times - sml

How is it possible to composite function f n times in ML?
composite two times;f(fx)
composite three times;f(f(fx)))
composite n times; f(f(f(f.....(fx)))))))
I have tried;
fun composite f g =
let h x = f(g x)
in h end;
fun repeat f n =
if n = 0 then x
else composite f repeat(f (n - 1));
Thank you

When you write recursive functions, divide your problem into general, recursive cases, and base cases that don't require recursion. For example, composing a function with itself n times sounds like the base case might be either when n = 0 or when n = 1 (either could work; I'll get back to that).
I'd encourage pattern matching, but when recursing integers, if-then-else do seem just as simple. In any case, all the examples have been written in both styles. A simple skeleton might be:
fun repeat f n =
if n = 0
then ?
else ?
fun repeat f 0 = ?
| repeat f 1 = ?
| repeat f n = ?
On functions that return functions
I imagine some of the difficulty here is that repeat must return a function. Syntactically you can achieve that in various ways. Like John suggests, you might write it by extending repeat with x:
fun repeat f n x =
if n = 1
then f x
else ...
fun repeat f 1 x = f x
| repeat f n x = ...
to which the natural, but slightly weird, interpretation is "repeat is a function that takes three arguments; the function f, the number of times it must be applied n, and f's argument x (?!)".
Alternatively, one might also write it like
fun repeat f n =
if n = 1
then (fn x => f x)
else ...
fun repeat f 1 = (fn x => f x)
| repeat f n = ...
which might be interpreted like "repeat is a function that takes two arguments; the function f and the number of times it must be applied n, and returns a function that applies f to its argument n times."
Those definitions are really equivalent. You'll see that by translating the description into types:
val repeat : ('a -> 'a) -> int -> 'a -> 'a
val repeat : ('a -> 'a) -> int -> ('a -> 'a)
That last parenthesis is implied in the first type signature.
Sometimes it helps to think of functions with many curried arguments as "functions with many arguments", and other times it helps to think of them as "functions that return functions that take yet other arguments". And repeat seems to be a mixture of this; n is best thought of as "a second argument", but x is best thought of as "the argument that the function we're returning takes".
With this preference, and a preference for pattern matching, my recommended basis would be:
fun repeat f 0 = ...
| repeat f 1 = f
| repeat f n = ...
since (fn x => f x) and f are really one and the same function.
On the base case and the recursive case
You write:
fun repeat f n =
if n = 0 then x
else composite f repeat(f (n - 1));
The x in then x has the wrong type, since repeat f n must return a function. See above.
The case when applying f zero times is a little tricky. Whatever the result is, it should be the case that repeat f 0 should give the same result regardless of f. Or put differently, that f isn't applied, although the repeat f 0 does need to return something.
On the recursive case, really, you're just messing up the parentheses. John revealed the o operator that is Standard ML's built-in version of composite which I'll prefer, too:
composite f (repeat f (n-1))
f o repeat f (n-1)
What you need to know about parentheses in Standard ML: You add them mostly to group things. When you write composite f repeat (f (n-1)), what you're saying is: "composite is a three-argument function that takes f, repeat and f (n-1) as an argument" and "f is a function that takes integers as arguments."
When what you really wanted to say was "composite takes f and the result of composing f with itself n–1 times, and composes those." It's a classic mistake when you come from languages that expect function calls to look like foo(arg1, arg, arg3) and one thinks this translates into foo(arg1 arg arg3) when in fact you wanted foo arg1 arg2 arg3. In Standard ML, this parenthesis forces arg1 to be treated as a function and applies it to arg2 and arg3, and applies foo to the result of that. Whoops!

Your ideas are close to being correct. You could use currying to make them work:
fun composite f g x = f(g(x));
SML infers its type as:
val composite = fn : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
which is exactly right for composition. Function application is left-associative, so
composite f g x
parses as
(composite f g) x
the function definition thus reads as giving the meaning of applying the function (composite f g) to an argument x. The meaning is, of course, to return the value f(g(x)).
You can test it:
fun square x = x*x
fun increment x = x + 1
val h = composite increment square
Then e.g. h 5 evaluates to 26 as expected.
A similar tweak works for your second definition. It could begin:
fun repeat f n x =
since this seems like homework, I'll leave the details to you, but your current attempt is rather close to a correct solution.
Having said all this, you should know that composition is a built-in operator in SML, denoted by the lowercase o, and that (op o) could be used in your second definition in place of composite.

Related

How can you make a function that returns a function in ocaml

for an example, if a function receives a function as a factor and iterates it twice
func x = f(f(x))
I have totally no idea of how the code should be written
You just pass the function as a value. E.g.:
let apply_twice f x = f (f x)
should do what you expect. We can try it out by testing on the command line:
utop # apply_twice ((+) 1) 100
- : int = 102
The (+) 1 term is the function that adds one to a number (you could also write it as (fun x -> 1 + x)). Also remember that a function in OCaml does not need to be evaluated with all its parameters. If you evaluate apply_twice only with the function you receive a new function that can be evaluated on a number:
utop # let add_two = apply_twice ((+) 1) ;;
val add_two : int -> int = <fun>
utop # add_two 1000;;
- : int = 1002
To provide a better understanding: In OCaml, functions are first-class
values. Just like int is a value, 'a -> 'a -> 'a is a value (I
suppose you are familiar with function signatures). So, how do you
implement a function that returns a function? Well, let's rephrase it:
As functions = values in OCaml, we could phrase your question in three
different forms:
[1] a function that returns a function
[2] a function that returns a value
[3] a value that returns a value
Note that those are all equivalent; I just changed terms.
[2] is probably the most intuitive one for you.
First, let's look at how OCaml evaluates functions (concrete example):
let sum x y = x + y
(val sum: int -> int -> int = <fun>)
f takes in two int's and returns an int (Intuitively speaking, a
functional value is a value, that can evaluate further if you provide
values). This is the reason you can do stuff like this:
let partial_sum = sum 2
(int -> int = <fun>)
let total_sum = partial_sum 3 (equivalent to: let total_sum y = 3 + y)
(int = 5)
partial_sum is a function, that takes in only one int and returns
another int. So we already provided one argument of the function,
now one is still missing, so it's still a functional value. If that is
still not clear, look into it more. (Hint: f x = x is equivalent to
f = fun x -> x) Let's come back to your question. The simplest
function, that returns a function is the function itself:
let f x = x
(val f:'a -> 'a = <fun>)
f
('a -> 'a = <fun>)
let f x = x Calling f without arguments returns f itself. Say you
wanted to concatenate two functions, so f o g, or f(g(x)):
let g x = (* do something *)
(val g: 'a -> 'b)
let f x = (* do something *)
(val f: 'a -> 'b)
let f_g f g x = f (g x)
(val f_g: ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>)
('a -> 'b): that's f, ('c -> 'a): that's g, c: that's x.
Exercise: Think about why the particular signatures have to be like that. Because let f_g f g x = f (g x) is equivalent to let f_g = fun f -> fun g -> fun x -> f (g x), and we do not provide
the argument x, we have created a function concatenation. Play around
with providing partial arguments, look at the signature, and there
will be nothing magical about functions returning functions; or:
functions returning values.

Understanding Basic recursion in OCaml

Hello guys I am trying to make a simple recursive method that simply takes in an accumulator and a target value. Then add one to the accumulator until it reaches the target value. I am very new to Ocaml but have a decent background in java.
I wrote up a quick snippet of code that shows what I want to do in java:
public static int rec(int acc,int target) {
if (acc == target) {
return 0;
} else {
return rec(acc+1, target);
}
}
here is my attempt to mimic this code in Ocaml:
let h_sequence x =
let rec helper acc x = function
| acc -> x
| _ -> helper acc+1 x
in
helper 0 x;;
however I get the following error:
Error: This expression has type 'a -> 'b -> 'a
but an expression was expected of type int
Here is how I am trying to understand the Ocaml code. So we have a function h_sequence that has a paramater x. Inside of the function h_sequence we have a recursive function named helper which has two paramaters acc and x. If acc = x then return x. Else start the recursion by passing in helper, add one to the acc and then return x. And after the in it is passing the helper function, setting 0 for the acc and setting x as x. Please let me know if my logic is off. Any help will be much appreciated!
edit new code:
let h_sequence x =
let rec helper acc x =
if acc = x then
acc
else
helper (acc+1) x
in
helper 0 x;;
As #Flux says, your helper function has 3 parameters. You should also be aware that the pattern acc will match all values. Patterns consist essentially of constants, and any names appearing in a pattern will match (and be bound to) any corresponding value.
To compare x against acc you should just use an if statement.
Since you don't really want to use pattern matching, you can simplify things by removing function. You'll end up with something like this for the helper function:
let rec helper acc x =
if x = acc then (* One of the cases *)
else (* The other case *)
... we have a recursive function named helper which has two parameters acc and x.
You are getting the error because the recursive function helper actually has three "parameters": acc, x, and another "parameter" that that is matched using function. The error message has given you this clue ('a -> 'b -> 'a).
Let's now look at the helper function:
let rec helper acc x = function
| zzz -> x (* Equivalent to `| _ -> x` *)
| _ -> helper acc+1 x
Mistakes:
function does pattern matching. Everything will match the pattern zzz, which means that the next pattern (| _ -> helper acc+1 x) is useless because it will never be matched. Note that I've changed the pattern's name from your acc to zzz in order to emphasize that function actually matching patterns.
helper acc+1 x is equivalent to (helper acc) + 1 x, which is not what you want. It should be helper (acc+1) x instead.
Solution
let rec helper acc x =
if acc >= x then 0
else helper (acc+1) x
You should use >= instead of = to handle the case where x is negative.

OCaml Function that takes in functions

I need to write a pipe function in OCaml such that pipe [f1;...;fn] (where f1,...,fn are functions!) returns a function f such that for any x, f x computes fn(...(f2(f1 x))).
I need to write it using List.fold_left and need to fill in the parameter of the function
let pipe fs =
let f a x = "fill in this part" in
let base = fun x ->x in
List.fold_left f base fs;;
I already filled in the base. If the first parameter to pipe is an empty list, it returns the second parameter. Ex: pipe [] 3 = 3.
i know for the let f a x part I want to perform function x of the accumulated functions a.
I'm just not sure how to write that. I wrote let f a x = x a but that gave me an error when i tested
pipe [(fun x -> x+x); (fun x -> x + 3)] 3
it should run x+x on 3 then run x+3 on the result and give me 9 but it gave it a type error when i tried to use let f a x = x a
for the fill in part
# let _ = pipe [(fun x -> x+x); (fun x -> x + 3)] 3;;
File "", line 1, characters 24-25:
Error: This expression has type 'a -> 'a
but an expression was expected of type int
What is the correct format to create a function that takes in 2 functions and runs them on each other. Ex: make a function that takes in functions a and b and runs b on the result of a.
To evaluate (fold_left g init fs) x:
when fs is empty, (fold_left g init fs) x = init x. In your case, you want it to be x.
when fs = fs' # [fn]: according to what you would like to be true, the expression should evaluate to
fn (fold_left g init fs' x) but using the definition of fold_left it evaluates also to (g (fold_left g init fs') fn) x.
Hence if the following equations are true:
init x = x
(g k f) x = f (k x)
the problem is solved. Hence, let us define init = fun x -> x and
g k f = fun x -> f (k x).
Well, base is a function like this fun x -> ....
Similarly, your function f needs to return a function, so assume it returns something that looks like this:
fun z -> ...
You have to figure out what this function should be doing with its argument z.
figured it out just needed that z in there for a and x to call

What does function return when "function times zero" in functional programming?

I am stuck with this SML assignment. I am trying to create a compound function (fun compound n f). It's supposed to apply the function f on itself for n times for example, compound 3 f will equal to f(f(f(x))). I got it to work except for case where n is zero. I asked the professor but he won't tell me a direct answer. He tried to give me an hint that "what's function times zero?" I still can't figure that out either. Can stackoverflow figure it out?
Thanks.
My code:
fun compound n f =
if n < 2 then
if n = 0 then fn x => f x else fn x => f x
else fn x => f(compound (n-1) f(x));
example:
val fnc = fn x => x + 1; (* example function to be used *)
compound 5 fnc(10); (* will return 15 which is correct*)
compound 0 fnc(10); (* returns 11, should be 10 *)
Answer:
fun compound n f =
if n < 2 then
if n = 0 then fn x => x else fn x => f x
else fn x => f(compound (n-1) f(x));
I won't give you the final answer because I don't like to upset teachers ;) However, I'll try a derivation that I believe you'll find easy to complete.
Let's start from a very simple case. Let's "reimplement" function application, i.e., let's write a function that takes a function and an argument and apply the first param to the second one:
fun apply f a = f a
Let's use a contrived function, that increments integers, for testing:
- fun inc n = n + 1;
val inc = fn : int -> int
- inc 1;
val it = 2 : int
- apply inc 1;
val it = 2 : int
Now, let's write apply2, a function which takes a function and an argument and applies the param function two times to the argument:
fun apply2 f a = f (f a)
Let's test it with inc:
- apply2 inc 1;
val it = 3 : int
Seems to be working. As you might expect, we'd now implement apply3, apply4 and so on. Let's see some of them at once:
fun apply f a = f a
fun apply2 f a = f (f a)
fun apply3 f a = f (f (f a))
fun apply4 f a = f (f (f (f a)))
It looks like we can rewrite later ones in terms of the earlier ones:
fun apply2 f a = f (apply f a)
fun apply3 f a = f (apply2 f a)
fun apply4 f a = f (apply3 f a)
We can even rewrite apply:
fun apply f a = f (apply0 f a)
Remember the previous definition of apply, they're equivalent:
fun apply f a = f a
So, what should apply0 be?
fun apply0 f a = ...
What is the base case for this algorithm? i.e. at what value of n does the recursion terminate? When it terminated what do you return? Think about what you would want to return if f is not applied to x. In the context of your example, if fnc is applied to 10 zero times, what should be returned?
fun compound n f =
(* If n equals the termination value, then return the base case*)
if n = ?
else fn x => f(compound (n-1) f(x));
There is a pattern here that exists in the base case for recursive algorithms. For example, what is the sum of a list with no elements? Or, what is the length of a list with no elements?

Haskell: How to simplify or eliminate liftM2?

Consider the following code I wrote:
import Control.Monad
increasing :: Integer -> [Integer]
increasing n
| n == 1 = [1..9]
| otherwise = do let ps = increasing (n - 1)
let last = liftM2 mod ps [10]
let next = liftM2 (*) ps [10]
alternateEndings next last
where alternateEndings xs ys = concat $ zipWith alts xs ys
alts x y = liftM2 (+) [x] [y..9]
Where 'increasing n' should return a list of n-digit numbers whose numbers increase (or stay the same) from left-to-right.
Is there a way to simplify this? The use of 'let' and 'liftM2' everywhere looks ugly to me. I think I'm missing something vital about the list monad, but I can't seem to get rid of them.
Well, as far as liftM functions go, my preferred way to use those is the combinators defined in Control.Applicative. Using those, you'd be able to write last = mod <$> ps <*> [10]. The ap function from Control.Monad does the same thing, but I prefer the infix version.
What (<$>) and (<*>) goes like this: liftM2 turns a function a -> b -> c into a function m a -> m b -> m c. Plain liftM is just (a -> b) -> (m a -> m b), which is the same as fmap and also (<$>).
What happens if you do that to a multi-argument function? It turns something like a -> b -> c -> d into m a -> m (b -> c -> d). This is where ap or (<*>) come in: what they do is turn something like m (a -> b) into m a -> m b. So you can keep stringing it along that way for as many arguments as you like.
That said, Travis Brown is correct that, in this case, it seems you don't really need any of the above. In fact, you can simplify your function a great deal: For instance, both last and next can be written as single-argument functions mapped over the same list, ps, and zipWith is the same as a zip and a map. All of these maps can be combined and pushed down into the alts function. This makes alts a single-argument function, eliminating the zip as well. Finally, the concat can be combined with the map as concatMap or, if preferred, (>>=). Here's what it ends up:
increasing' :: Integer -> [Integer]
increasing' 1 = [1..9]
increasing' n = increasing' (n - 1) >>= alts
where alts x = map ((x * 10) +) [mod x 10..9]
Note that all refactoring I did to get to that version from yours was purely syntactic, only applying transformations that should have no impact on the result of the function. Equational reasoning and referential transparency are nice!
I think what you are trying to do is this:
increasing :: Integer -> [Integer]
increasing 1 = [1..9]
increasing n = do p <- increasing (n - 1)
let last = p `mod` 10
next = p * 10
alt <- [last .. 9]
return $ next + alt
Or, using a "list comprehension", which is just special monad syntax for lists:
increasing2 :: Integer -> [Integer]
increasing2 1 = [1..9]
increasing2 n = [next + alt | p <- increasing (n - 1),
let last = p `mod` 10
next = p * 10,
alt <- [last .. 9]
]
The idea in the list monad is that you use "bind" (<-) to iterate over a list of values, and let to compute a single value based on what you have so far in the current iteration. When you use bind a second time, the iterations are nested from that point on.
It looks very unusual to me to use liftM2 (or <$> and <*>) when one of the arguments is always a singleton list. Why not just use map? The following does the same thing as your code:
increasing :: Integer -> [Integer]
increasing n
| n == 1 = [1..9]
| otherwise = do let ps = increasing (n - 1)
let last = map (flip mod 10) ps
let next = map (10 *) ps
alternateEndings next last
where alternateEndings xs ys = concat $ zipWith alts xs ys
alts x y = map (x +) [y..9]
Here's how I'd write your code:
increasing :: Integer -> [Integer]
increasing 1 = [1..9]
increasing n = let allEndings x = map (10*x +) [x `mod` 10 .. 9]
in concatMap allEndings $ increasing (n - 1)
I arrived at this code as follows. The first thing I did was to use pattern matching instead of guards, since it's clearer here. The next thing I did was to eliminate the liftM2s. They're unnecessary here, because they're always called with one size-one list; in that case, it's the same as calling map. So liftM2 (*) ps [10] is just map (* 10) ps, and similarly for the other call sites. If you want a general replacement for liftM2, though, you can use Control.Applicative's <$> (which is just fmap) and <*> to replace liftMn for any n: liftMn f a b c ... z becomes f <$> a <*> b <*> c <*> ... <*> z. Whether or not it's nicer is a matter of taste; I happen to like it.1 But here, we can eliminate that entirely.
The next place I simplified the original code is the do .... You never actually take advantage of the fact that you're in a do-block, and so that code can become
let ps = increasing (n - 1)
last = map (`mod` 10) ps
next = map (* 10) ps
in alternateEndings next last
From here, arriving at my code essentially involved writing fusing all of your maps together. One of the only remaining calls that wasn't a map was zipWith. But because you effectively have zipWith alts next last, you only work with 10*p and p `mod` 10 at the same time, so we can calculate them in the same function. This leads to
let ps = increasing (n - 1)
in concat $ map alts ps
where alts p = map (10*p +) [y `mod` 10..9]
And this is basically my code: concat $ map ... should always become concatMap (which, incidentally, is =<< in the list monad), we only use ps once so we can fold it in, and I prefer let to where.
1: Technically, this only works for Applicatives, so if you happen to be using a monad which hasn't been made one, <$> is `liftM` and <*> is `ap`. All monads can be made applicative functors, though, and many of them have been.
I think it's cleaner to pass last digit in a separate parameter and use lists.
f a 0 = [[]]
f a n = do x <- [a..9]
k <- f x (n-1)
return (x:k)
num = foldl (\x y -> 10*x + y) 0
increasing = map num . f 1