F#: Passing a function to Option.bind - function

I have a function great and it is implemented as below
let great y z = Option.bind (cons (Option.get z) >> Some) y
And I have the function apply as below
let apply f val =
match f with
| None -> None
| Some v -> Option.map v val
If I give the None value for the second parameter (z) it is giving me an error since Option.get z returns an error when it gets None.
I want to avoid this error without using if else blocks. I wonder is it possible to pass the great function to apply so that it can evaluate None when the given z parameter is None.
Any help would be appreciated.

If you want to execute the whole Option.bind ... thing only when z is Some, you can just use another Option.bind for that - that's exactly what bind is for:
let great y maybeZ =
Option.bind (fun z -> Option.bind (cons z >> Some) y) maybeZ
Or, to express it more elegantly:
let great maybeY maybeZ =
maybeZ |> Option.bind (fun z ->
maybeY |> Option.bind (cons z >> Some) )
The first line would then read like "bind maybeZ to z, and..."
In fact, I would probably do the same thing with y just for extra readability:
let great maybeY maybeZ =
maybeZ |> Option.bind (fun z ->
maybeY |> Option.bind (fun y ->
Some (z :: y) ) )
Alternatively, you can use Option.map2, which does exactly this: applies a function to two option-typed parameters when both are Some:
let great maybeY maybeZ =
Option.map2 (fun y z -> z :: y) maybeY maybeZ
And then you can eta-reduce it (but, sadly, only for maybeZ, due to the value restriction):
let great maybeY =
Option.map2 (fun y z -> z :: y) maybeY
Or you could get rid of the lambda instead if you just reversed the parameters:
let great maybeY maybeZ =
Option.map2 cons maybeZ maybeY

You can also write the great function using pattern matching like the apply function.
let great lOpt xOpt =
match lOpt, xOpt with
| Some l, Some x -> Some (x :: l)
| Some l, None -> Some l
| _ -> None

Related

Replacing functions in composite function in haskell

I'm trying to become familiar with Haskell and I was wondering if the following was possible and if so, how?
Say I have a set of functions {f,g,..} for which I was to define a replacement function {f',g',..}. Now say I have a function c which uses these functions (and only these functions) inside itself e.g. c x = g (f x). Is there a way to automatically define c' x = g' (f' x) without explicitly defining it?
EDIT: By a replacement function f' I mean some function that is conceptually relates to f by is altered in some arbitrary way. For example, if f xs ys = (*) <$> xs <*> ys then f' (x:xs) (y:ys) = (x * y):(f' xs ys) etc.
Many thanks,
Ben
If, as seems to be the case with your example, f and f' have the same type etc., then you can easily pass them in as extra parameters. Like
cGen :: ([a] -> [a] -> [a]) -> (([a] -> [a]) -> b) -> [a] -> b
cGen f g x = g (f x)
...which BTW could also be written cGen = (.)...
If you want to group together specific “sets of functions”, you can do that with a “configuration type”
data CConfig a b = CConfig {
f :: [a] -> [a] -> [a]
, g :: ([a] -> [a]) -> b
}
cGen :: CConfig a b -> [a] -> b
cGen (CConfig f g) = f . g
The most concise and reliable way to do something like this would be with RecordWildCards
data Replacer ... = R {f :: ..., g :: ...}
c R{..} x = g (f x)
Your set of functions now is now pulled from the local scope from the record, rather than a global definition, and can be swapped out for a different set of functions at your discretion.
The only way to get closer to what you want would to be to use Template Haskell to parse the source and modify it. Regular Haskell code simply cannot inspect a function in any way - that would violate referential transparency.

Haskell - redundant part in function

I have an intricate Haskell function:
j :: [Int]
j = ((\f x -> map x) (\y -> 3 + y) (\z -> 2*z)) [1,2,3]
My guess was that (\y -> 3 + y) (\z -> 2*z) will change to (\w -> 3 + 2*w) and together with f there should be print out the list [5,7,9].
When I checked with ghci I got [2,4,6] as a result.
Question: So is (\y -> 3 + y) a redundant expression here? If so, why?
I think you've gone wrong somewhere in the design of your function, but I'll give you an explanation of the mechanics going on here. Stick around for the detailed explanation if you still get stuck understanding.
Quick answer: Evaluating the expression
j = ((\f x -> map x) (\y -> 3 + y) (\z -> 2*z)) [1,2,3]
= ((\x -> map x) (\z -> 2*z)) [1,2,3]
= (map (\z -> 2*z)) [1,2,3] -- f := (\y -> 3 + y), x := (\z -> 2*z)
= [2,4,6]
You may see that when Haskell evaluates (\f x -> map x) (\y -> 3 + y), which it will because function applications are evaluated left-to-right, the substitution f := (\y -> 3 + y) is made, but f doesn't appear anywhere in the function, so it just becomes (\x -> map x).
Detailed answer: Left (and Right) associative operators
In Haskell we say that function application is left associative. This is to say, when we write a function application, it is evaluated like so:
function arg1 arg2 arg3 = ((function arg1) arg2) arg3
No matter what the types of the arguments are. This is called left associative because the brackets are always on the left.
You seem to expect your expression to behave like this:
(\f x -> map x) (\y -> 3 + y) (\z -> 2*z)
= (\f x -> map x) ((\y -> 3 + y) (\z -> 2*z)) -- Incorrect
However, as we've seen, functions associate left, not right as you assumed, and so your expression looks to Haskell like this:
(\f x -> map x) (\y -> 3 + y) (\z -> 2*z)
= ((\f x -> map x) (\y -> 3 + y)) (\z -> 2*z)
= (\x -> map x) (\z -> 2*z) -- Correct!
Notice that the brackets I put in to order the evaluation are on the left, not the right.
However, Haskell has defined a very useful right-associative function application operator, namely ($) :: (a -> b) -> a -> b. You could re-write your expression like so to obtain the result you seemed to expect.
(\f x -> map x) $ (\y -> 3 + y) (\z -> 2*z)
= (\f x -> map x) $ ((\y -> 3 + y) (\z -> 2*z)) -- Correct, though nonsensical.
However, as you'll notice, f still isn't referred to in (\f x -> map x) and so is ignored entirely. I'm not sure exactly what your goal was in making this function
Further issue: Lambda expressions & composition
I realise that another issue may be your understanding of lambda expressions. Consider this function:
f x = x + 2
We could re-write this as a lambda expression, like so:
f = \x -> x+2
However, what if we have two arguments? This is what we do:
g x y = x + y
g = \x -> (\y -> x+y)
The way Haskell models multiple arguments is called currying. You can see that the function actually returns another function, which then returns a function that finally returns what it should have. However, this notation is long and cumbersome, so Haskell provides an alternative:
g = \x y -> x + y
This may seem to be different, but in fact it is syntactic sugar for exactly the same expression as before. Now, looking at your first lambda expression:
\f x -> map x = \f -> (\x -> map x)
You can see that the argument f isn't actually referred to at all in the function, so if I apply something to it:
(\f x -> map x) foo
= (\f -> (\x -> map x)) foo
= \x -> map x
That's why your (\y -> 3 + y) is ignored; you haven't actually used it in your functions.
Furthermore, you expect the expression (\y -> 3 + y) (\z -> 2*z) to evaluate to \w -> 3 + 2*w. This is not true. The lambda on the left replaces each occurrence of y with (\z -> 2*z), so the result is the completely nonsensical 3 + (\z -> 2*z). How do you add a function to a number?!
What you're looking for is called composition. We have an operator in Haskell, namely (.) :: (b -> c) -> (a -> b) -> (a -> c) which can help you with this. It takes a function on the left and the right and creates a new function that 'pipes' the functions into each other. That is to say:
(\y -> 3 + y) . (\z -> 2*z) = \w -> 3 + 2*w
Which is what you're looking for.
Conclusion: Corrected expression
I think the expression you're looking for is:
j = ( (\x -> map x) $ (\y -> 3 + y) . (\z -> 2*z) ) [1,2,3]
Which is equivalent to saying:
j = map (\w -> 3 + 2*w) [1,2,3]
Since you seem to be having a lot of trouble with the more basic parts of Haskell, I'd recommend the quintessential beginner's book, Learn You a Haskell for Great Good.
It is because it goes the other way round, that is you apply (\f x -> map x) to (\y -> 3 + y) first. But
(\f x -> map x) something g
becomes
let f = something; x = g in map x
And this finally is
map g
So something doesn't appear in the resulting expression, since f is not mentioned anywhere right from the arrow.
If I understand you correctly, you want
(\f x -> map (f . x))
Additional note: From your argumentation, it looks like you have not grasped yet how beta reduction works.
For example, even if the expressions would be applied like you think:
(\y -> 3 + y) (\z -> 2*z)
the result would be
3 + (\z -> 2*z)
No, it is doubtful that this makes any sense, however, it's the way beta reduction works: It gives the part right from the arrow where every occurrence of a parameter is replaced by the actual argument.

How can I write this function only by using recursion in F#?

let rec n_cartesian_product = function
| [] -> [[]]
| x :: xs ->
let rest = n_cartesian_product xs
List.concat (List.map (fun i -> List.map (fun rs -> i :: rs) rest) x)
Hello! I wrote this function but I need to write it without using any List.* built-in functions. Since there's an inner function that calls an outer function, I assume I must define two mutually recursive functions.
Defining a concat function seemed easy:
let rec list_concat ( lst : 'a list list ) : 'a list =
match lst with
[] -> []
|x::xs -> x # (list_concat xs)
The problem is, I'm stuck at the definition of the functions which yield the argument for concat:
let rec fun_i rest =
match rest with
[] -> []
|x::xs -> fun_rs
and fun_rs =
fun_i :: fun_rs
I can't seem to devise a proper solution. Can you help me?
edit: for instance, given this input
[["A";"a"];["B";"b"];["C";"c"]]
I want this output:
[["A"; "B"; "C"]; ["A"; "B"; "c"]; ["A"; "b"; "C"]; ["A"; "b"; "c"];
["a"; "B"; "C"]; ["a"; "B"; "c"]; ["a"; "b"; "C"]; ["a"; "b"; "c"]]
N-Cartesian Product
To define the n cartesian product recursively, the easiest method is just to make recursive definitions of the functions used in your original (non-recursive) example:
let rec list_concat lst =
match lst with
|[] -> []
|x::xs -> x # (list_concat xs)
let rec list_map f lst =
match lst with
|[] -> []
|x::xs -> (f x) :: list_map f xs
let rec n_cartesian_product =
function
| [] -> [[]]
| x :: xs ->
let rest = n_cartesian_product xs
list_concat (list_map (fun head -> list_map (fun tail -> head :: tail) rest) x)
In terms of writing idiomatically in F#, it's best to write using more general functions (like fold), rather than making a lot of custom functions with explicit recursion. So, you could define some additional functions:
let list_collect f = list_concat << list_map f
let rec list_fold f acc lst =
match lst with
|[] -> acc
|hd::tl -> list_fold f (f acc hd) tl
let n_cartesian_product_folder rest first =
list_collect (fun head -> list_map (fun tail -> head :: tail) rest) first
Then we can redefine n_cartesian_product simply as:
let n_cartesian_product2 lst = list_fold (n_cartesian_product_folder) [[]] lst
If we were using F# core library functions (rather than custom recursive implementations) this approach would involve more standard code with less to go wrong.
Cartesian Product
(I'll leave this part here since apparently it was useful)
Define a function that takes a list of 'a and make a list of 'b * 'a where all of the things of type 'b are some supplied element y.
/// take a list of 'a and make a list of (y, 'a)
let rec tuplify y lst =
match lst with
|[] -> []
|x::xs -> (y, x) :: (tuplify y xs)
Then define a function that recurses through both my lists, calling tuplify on the current element of the first list and the entire second list and concat that with the recursive call to cartesian product.
/// cartesian product of two lists
let rec cartesianProduct lst1 lst2 =
match lst1 with
|[] -> []
|x::xs -> tuplify x lst2 # (cartesianProduct xs lst2)

iterate function in haskell

How can be iterate function modified that the result will be
f x, (f^2)x, (f^4)x, (f^8)x, ...
I'd be very happy if anybody could provide me with any suggestion.
Given, that f^x means f x-times applied to x I would say
iterate :: (a -> a) -> a -> [a]
iterate f x = f x : iterate (f . f) x
would suffice.
Alternative:
Prelude> map snd $ iterate (\(f,x) -> (f.f, f x)) ((+1),1)
[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,...

OCAML: Difference between let func a x = (a x);; and let func a x = ((fun a -> a) x);;?

I'm a little stuck on this assignment for OCAML. I'm trying to pass in a function and a value as a parameter into another function. For example, I have function called test that takes in (fun x -> x+x) and 3 as parameters. The function test should output 6, since 3 + 3 = 6. I know I can achieve something similar this by completing:
let func x = x + x;;
let a = func;;
let test a x = (a x);;
This way when I input, test a 5, I will get 10.
But when I change the statement to this, I get only the value I placed in for x. How do I get the (fun a -> a) to take in the value x?
let test a x = ((fun a -> a) x);;
fun a -> a is an anonymous identity function, it will always return its parameter. You could say:
let id = fun a -> a;;
id 3;;
=> 3
id (fun x -> x + x);;
=> (fun x -> x + x)
Note that in your
let test a x = ((fun a -> a) x);;
the first a and the other two as are different variables. The first one is never used again later. You can rewrite this line for easier understanding as:
let test a x = ((fun b -> b) x);;
How do I get the (fun a -> a) to take in the value x?
You are, and that's the problem. You're feeding your x to an identity function, and getting x back. What you want to do is feed the x to your a function, and that's what you did in your first attempt:
let func x = x + x;;
let test a x = a x;;
test func 3;;
=> 6
With functional languages in simple cases it is often helpful to write the expression in a form similar to lambda calculus and do the reductions manually (noting which reductions you are using). You can still use OCaml syntax as a simplified version of lambda calculus
So in the case of your example this would become:
let test a x = ((fun a -> a ) x);;
=> let test a x = ((fun b -> b ) x);; (* Variable renamed (alpha equivalence) *)
=> let test a y = ((fun b -> b ) y);; (* Variable renamed (alpha equivalence) *)
let func x = x + x;;
Note that these steps only serve to make sure, that we will later on have no variables with the same name, referring to different values. These steps can be left out, but I personally like working with unique variables much better.
test func 5
=> test (fun x -> x + x) 5 (* Variable func inserted (beta reduction) *)
=> (fun a y -> ((fun b -> b) y) (fun x -> x + x) 5 (* Variable test inserted *)
=> (fun y -> (fun b -> b) y) 5 (* Variable a inserted *)
=> ((fun b -> b) 5 (* Variable y inserted *)
=> 5 (* Variable b inserted *)
The final result is 5. Attempting this at first will seem very unusual and hard, but get's easier very fast. If you do something like this a couple of time you will get much better at understanding common functional patterns and reasoning about your program structure.
Have a look at this article for more examples on this.
Also note, that with a little more effort, this works backward as well. Although this usually is not as helpful as doing it in the same direction as the compiler.