I would like to implement a function which gets as input f g a when f g are lambda functions and a is a parameter. The function should do as following:
fun foo f g a = if (g a) then (f a) else a;
> val foo = fn : ('a -> 'a) -> ('a -> bool) -> 'a -> 'a
Is it possible to somehow replace if-else with andalso,orelse, or some other method? I would like to implement a function without using if-else statements.
Edit: Looking for a way to combine two functions, one of them is 'a -> 'a while the other one is 'a -> bool.
if for some weird reason you don't want to use if-else you could pattern match to true/false. E.g. like that:
fun bar f g a = case (g a) of
true => (f a)
| false => a;
fun bari f g a = (fn true => f a | false => a)(g a);
But as Simon Shine already mentioned you may want to rephrase your question and describe the problem in a bigger picture if this is not what you are looking for.
Related
I noticed that I cannot do the following in OCaml:
# let foo (f : 'a -> unit) = f 1; f "s";;
Error: This expression has type string but an expression was expected of type
int
In Haskell, this could be resolved by universally quantifying the input function f using Rank2Types:
{-# LANGUAGE Rank2Types #-}
foo :: (forall a. a -> ()) -> ()
foo f = let a = f 1 in f "2"
How can I get similar exposure to this in OCaml?
OCaml only supports semi-explicit higher-rank polymorphism: polymorphic functions arguments must be boxed either inside a record with polymorphic field:
type id = { id: 'a. 'a -> 'a }
let id = { id=(fun x -> x) }
let f {id} = id 1, id "one"
or inside an object
let id' = object method id: 'a. 'a -> 'a = fun x -> x end
let f (o: <id:'a. 'a -> 'a>) = o#id 1, o#id "one"
Beyond the syntactic heaviness, this explicit boxing of polymorphic functions has the advantage that it works well with type inference while still requiring only annotations at the definition of record types or the methods.
I'm trying to work out what specifically lwt is doing in a couple of examples:
If I have:
let%lwt x = f () in
let%lwt y = g () in
return ()
Does this run f then g, or since y doesn't rely on x will it run both in parallel?
That particular example runs f () and g () in sequence, i.e. g () doesn't start until after the promise returned by f () is resolved.
The way to see this is, when looking at
let%lwt x = e in
e'
to realize that e' becomes the body of a callback, that will run only when x is available. So, in the code in the question, Lwt first sees:
(* Do this first. *)
let%lwt x = f () in
(* Do this once is available. *)
let%lwt y = g () in
return ()
and, once x is available, it is left with
(* Do this next. *)
let%lwt y = g () in
(* Do this once y is available. *)
return ()
To avoid this serialization, call f () and g () first, without any intervening let%lwt, bind variables to the promises x', y' these functions return, and wait on the promises:
let x' = f () in
let y' = g () in
let%lwt x = x' in
let%lwt y = y' in
return ()
(And to answer the title, Lwt does not use data dependencies. I don't think a library could have access to this kind of data dependency information).
In your code, no, because you are using Lwt.t as monad, rather than as an applicative.
Monads
You're probably already familiar with asynchronous IO and the functions Lwt.bind : 'a Lwt.t -> ('a -> 'b Lwt.t) -> 'b Lwt.t and Lwt.return : 'a -> 'a Lwt.t. Just in case, though, I will give a brief recap:
Lwt.bind promise callback awaits promise, and upon resolution, calls callback with the result, getting back another promise.
Lwt.return data creates a promise that resolves to data.
A monad is a generic type 'a t that has some function bind : 'a t -> ('a -> 'b t) -> 'b t and some function return : 'a -> 'a t. (These functions must also follow certain laws, but I digress.) Obviously, the type 'a Lwt.t with the functions Lwt.bind and Lwt.return form a monad.
Monads are a common functional programming pattern when one wants to represent some kind of "effect" or "computation," in this case asynchronous IO. Monads are powerful because the bind function lets later computations depend on the results of earlier ones. If m : 'a t represents some computation that results in 'a, and f : 'a -> 'b t is a function that uses an 'a to perform a computation that results in a 'b, then bind m f makes f depend on the result of m.
In the case of Lwt.bind promise callback, callback depends on the result of promise. The code in callback cannot run until promise is resolved.
When you write
let%lwt x = f () in
let%lwt y = g () in
return ()
you are really writing Lwt.bind (f ()) (fun x -> Lwt.bind (g ()) (fun y -> return ())). Because g () is inside the callback, it is not run until f () is resolved.
Applicatives
A functional programming pattern related to the monad is the applicative. An applicative is a generic type 'a t with a function map : ('a -> 'b) -> 'a t -> 'b t, the function return : 'a -> 'a t, and a function both : 'a t * 'b t -> ('a * 'b) t. Unlike monads, however, applicatives need not have bind : 'a t -> ('a -> 'b t) -> 'b t, meaning that with applicatives alone, later computations cannot depend on previous ones. All monads are applicatives, but not all applicatives are monads.
Because g () does not depend on the result of f (), your code can be rewritten to use both:
let (let*) = bind
let (and*) = both
let* x = f ()
and* y = g () in
return ()
This code translates to bind (fun (x, y) -> return ()) (both (f ()) (g ())). f () and g () appear outside the callback to bind, meaning that they are run immediately and can await in parallel. both combines f () and g () into a single promise.
The (let*) and (and*) operators are new to OCaml 4.08. If you are using an earlier version of OCaml, you can just write the translation directly.
Lwt.both in the documentation
The Lwt home page contains a code snippit using let* and and*
"Binding operators" (let* and and*) in the OCaml manual
I am trying to understand difference between these two;
val my_fun = length o List.filter (fn (item) => item = #"a") o String.explode
This one can be invoked (my_fun "name" will return 1) and works fine. I am trying to understand why following is not working
length o (List.filter (fn (item) => item = #"a" ) (String.explode "name"))
Definition of function composition in sml
f o g = f(g(x))
In the second form what we do is ( I think)
length ([#"a"])
You seem to be confusing function composition with function application.
Composition is a higher-order function which takes two functions, f and g, of compatible types and returns another function -- the function which is computed by first applying the g to a value and then applying f to the result. o is a built-in operator, but if you wanted to define composition yourself it would be something like
fun compose (f,g) x = f(g(x))
this has type fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b (which is exactly the type you get when you type (op o); in the REPL). Note that the return value of compose is 'c -> 'b, which is a function type.
length o List.filter (fn (item) => item = #"a") o String.explode
makes perfect sense since the types are compatible and composition is right-associative.
On the other hand, as you already note,
length o (List.filter (fn (item) => item = #"a" ) (String.explode "name"))
would be equivalent to
length o [#"a"]
That really doesn't make sense. What would it even mean to compose a function with a list. A list isn't a function. It does make sense to apply length to that list, which is what you seem to expect.
Application is simply juxtaposition, so all you would need to do is write
length (List.filter (fn (item) => item = #"a" ) (String.explode "name"))
Which reduces to length [#"a"] and from thence to 1.
If you wanted to write your own apply function you would write:
def apply f x = f x
This might strike you as superficially similar to compose but its type is radically different: fn : ('a -> 'b) -> 'a -> 'b. Composition involves application, but it isn't the same thing.
I have to write a function to print a list in SML with the following type signature :
val printGenList = fn : ('a -> 'b) -> 'a list -> unit
The "printGenList" will take two arguments function f and list l and applies the function f to each element of list l recursively.
Since I am new to ML, I am not able to implement it but I tried this code which is giving the different type signature
fun printGenList = CONS(fib, fn => printGenList fib fibs);
where, fib is
fun fib a b = CONS(a, fn => fib b (a+b));
and fibs is
val fibs = fib 0 1;
What you're trying to do is impossible, ML's type system doesn't support this type of polymorphism. If you Google, there are some printf libraries for SML that show you how to approach this -- for each type t that you want to print, you'll need to define a separate t -> unit function and compose them together.
EDIT: Oh, I see, you're not looking for a function to print lists of any type, you're looking for a higher order function that applies an 'a->'b function to every element of a list... my mistake. This is what you need:
val rec printGenList =
fn (f : 'a -> 'b) =>
(fn [] => ()
| x::xs => (f(x); printGenList f xs))
I need to find a way to combine two functions and output them as one.
I have the following code where take in a list of function ('a->'a) list then output a function ('a->'a) using the List.fold_left.
I figured out the base case, but I tried a lot of ways to combine two functions. The output should have the type ('a -> 'a) list -> ('a -> 'a).
example output:
# pipe [] 3;;
- : int = 3
# pipe [(fun x-> 2*x);(fun x -> x + 3)] 3 ;;
- : int = 9
# pipe [(fun x -> x + 3);(fun x-> 2*x)] 3;;
- : int = 12
function:
let p l =
let f acc x = fun y-> fun x->acc in (* acc & x are functions 'a->'a *)
let base = fun x->x in
List.fold_left f base l
Since you know that you have to use a left fold, you now have to solve a fairly constrained problem: given two functions of type 'a -> 'a, how do you combine them into a single function of the same type?
In practice, there is one general way of combining functions: composition. In math, this is usually written as f ∘ g where f and g are the functions. This operation produces a new function which corresponds to taking an argument, applying g to it and then applying f to the result. So if h = f ∘ g, then we can also write this as h(x) = f(g(x)).
So your function f is actually function composition. (You should really give it a better name than f.) It has to take in two functions of type 'a -> 'a and produce another function of the same type. This means it produces a function of one argument where you produce a function taking two arguments.
So you need to write a function compose (a more readable name than f) of type ('a -> 'a) -> ('a -> 'a) -> ('a -> 'a). It has to take two arguments f and g and produce a function that applies both of them to its argument.
I hope this clarifies what you need to do. Figuring out exactly how to do it in OCaml is a healthy exercise.