I am in front of quite a challenge here, and hope that you can provide a little help.
I have tried and searched a lot, but without success.
Here is the problem:
Two lists
List1 : [a1; a2; ...; an]
List2 : [b1; b2; ...; bn]
What is the function that returns a list of ALL the interleaves possible of the two lists RESPECTING the order within each list.
For example :
myFunction [1; 2] ['a'; 'b'; 'c'] = [
[1; 2; 'a'; 'b'; 'c'];
[1; 'a'; 2; 'b'; 'c'];
[1; 'a'; 'b'; 2; 'c'];
[1; 'a'; 'b'; 'c'; 2];
['a'; 1; 2; 'b'; 'c'];
['a'; 1; 'b'; 2; 'c'];
['a'; 1; 'b'; 'c'; 2];
['a'; 'b'; 1; 2; 'c'];
['a'; 'b'; 1; 'c'; 2];
['a'; 'b'; 'c'; 1; 2]
]
For those who have noticed, it is basically thinking about 2 concurrent programs, and ALL the executions possible when the 2 programs are launched (1 is always before 2, a is always before b and before c, otherwise, all interleaves are possible)
I hope that I was clear, and that you can help me.
Thank you a lot.
Since it is homework, here are a few hints:
1). The function would take two lists of same type 'a list and return an 'a list list.
val interleave: 'a list -> 'a list -> 'a list list
2). If one list is empty, the result is a singleton list consisting of the other one.
3). Let's say you would like to execute interleave on two non-empty lists x::xs and y::ys. There are two kinds of interleaving. The first kind has x as the head of resulting lists, you would put x into the beginning of any list returning from interleave xs (y::ys). The second kind has y as the new head, you would prepend y into any list obtaining from interleave (x::xs) ys.
With these hints, I think you are able to create a recursive function with a few pattern matching cases to solve the problem.
(* Each interleaving of non-empty lists lst1 = [x1; x2; ...; xm]
and lst2 = [y1; y2; ...; yn] begins either with x1 or with y1.
Thus we may get all the interleavings as follows:
1. Compute all interleavings of [x2; ...; xm] and [y1; ...; yn]
and prepend x1 to each one of them.
2. Compute all interleavings of [x1; ...; xm] and [y2; ...; yn]
and prepend y1 to each one of them.
Append the lists obtained in steps 1 and 2 to get all possible
interleavings. The border cases is when either one of the lists
is empty, but that is easy to figure out. Here is the corresponding
code.
*)
let rec interleave lst1 lst2 =
match lst1, lst2 with
| [], ys -> [ys]
| xs, [] -> [xs]
| x :: xs, y :: ys ->
(List.map (fun zs -> x :: zs) (interleave xs (y::ys))) #
(List.map (fun zs -> y :: zs) (interleave (x::xs) ys))
Test case:
# interleave [1;2] [100;200;300] ;;
- : int list list =
[[1; 2; 100; 200; 300]; [1; 100; 2; 200; 300]; [1; 100; 200; 2; 300];
[1; 100; 200; 300; 2]; [100; 1; 2; 200; 300]; [100; 1; 200; 2; 300];
[100; 1; 200; 300; 2]; [100; 200; 1; 2; 300]; [100; 200; 1; 300; 2];
[100; 200; 300; 1; 2]]
NB: In Ocaml lists are monomorphic so we cannot interleave strings and integers, as was suggested in the question. Or to put it in a different way, for that we would have to use
a sum type.
Related
Input: [x1; x2; ... ; xn]
Output ([x1; x3; ...; xn], [x2; x4; ...; xn], [x3; x5; ...; xn], ....)
What I have so far is:
let rec split = function
| x0 :: x1 :: xs -> (x0::xs) :: split(x1::xs)
| _ -> []
Which yields:
Input: [1;2;3;4;5;6]
Output: [[1; 3; 4; 5; 6]; [2; 4; 5; 6]; [3; 5; 6]; [4; 6]; [5]]
I don't quite see how I can build a tuple of lists recursively.
Any ideas?
I don't know why u want to do this, and if its some sort of exercise/homework I don't want to give you the answer BUT I will give you a hint, best start with something that does something sort of in the right direction.
This code takes a list and in a very unnecesary convoluted way, recursive returns a tuple of three of them.
let rec tripleList : List<'a> -> (List<'a> * List<'a> * List<'a>) =
function
| [] -> ([],[],[])
| (x :: xs) ->
let (tail1,tail2,tail3) = tripleList xs
(x :: tail1,x :: tail2,x :: tail3)
> tripleList [1..10];;
val it : List<int> * List<int> * List<int> =
([1; 2; 3; 4; 5; 6; 7; 8; 9; 10], [1; 2; 3; 4; 5; 6; 7; 8; 9; 10],
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10])
you don't need to do the whole thing as a single function either, you could create 3 functions, 1 that builds each part of the tuple, and then a fourth function that calls the 3 functions to assemble the answer. That may be a simpler place to start.
So a similar sort of thing would be...
let rec tripleList1 : List<'a> -> List<'a> =
function
| [] -> []
| (x :: xs) ->
(x :: tripleList1 xs)
let rec tripleList2 : List<'a> -> List<'a> =
function
| [] -> []
| (x :: xs) ->
(2 * x :: tripleList2 xs)
let rec tripleList3 : List<'a> -> List<'a> =
function
| [] -> []
| (x :: xs) ->
(3 * x :: tripleList3 xs)
let tripleList : List<int> -> (List<int> * List<int> * List<int>) =
fun xs ->
(tripleList1 xs,tripleList2 xs,tripleList3 xs)
I prefer the first approach, but both are perfectively valid, and makes the distinction between the need for recursive functions to create the recusrive data structure List<'a>, whilst the tuple just requires a simple standalone function
so maybe try to write a function that takes.
[1,2,3,4,5,6,7] -> [1,3,5,7]
and then see if you can generalise that, and then assemble the pieces in another function
(note don't be misled by my example, they have the right structure but they fundamentally don't do what you need, you need to filter out values somehow in each part)
I am practicing on matrix at the moment but I am not really sure on the most efficient way to resolve some of the problems I encounter.
My first "problem" is to optimize a function. What I try to do is to iterate trough the 'a matrix which is a 'a array array.
For each line identified by an integer between 0 and 4 (the matrix has a size of (5,10)), I count how many "one" there is.
I had to split it in three different functions but I was wondering if there is any more optimized way to solve this problem ?
let count m i =
let ret=Array.fold_left (fun x y -> if y=1 then x+1 else x) 0 (m.(i)) in
ret;;
let rec clear l =
match l with
|[]->[]
|(a,b)::[]->if b=0 then [] else (a,b)::[]
|(a,b)::c->if b=0 then clear c else (a,b)::clear c;;
let all_moves s =
match s with
|(a,_)->clear[(0,count a 0);(1,count a 1);(2,count a 2);(3,count a 3);(4,count a 4)];;
Second of all, my main problem is to iterate through the entire matrix at once.
I'm trying to count all the 1 in the matrix except for the line identified by param "i".
I tried several things but I'm really stuck at the moment.
let countall m i =
let ret=Array.fold_left (fun x y -> if pos != i then x + y else ())
(Array.fold_left (fun x y -> if y=1 then x+1 else x) 0 (m.(i)))
0 m in
ret;;
I would like to thank you in advance for your help and I thought I might give a matrix for you to test my functions:
let c = [|[|1; 1; 1; 1; 1; 0; 0; 0; 0; 0|]; [|1; 1; 1; 1; 1; 1; 1; 1; 0; 0|];
[|1; 1; 1; 1; 1; 1; 1; 1; 1; 0|]; [|1; 0; 0; 0; 0; 0; 0; 0; 0; 0|];
[|1; 1; 1; 1; 1; 1; 1; 1; 1; 1|]|]
Sincerely yours,
Rama
Some pointers:
Expressions of the form let ret = expr in ret can be simplified to expr. And the reverse application operator |> can often be used to elide trivial let expressions.
If a function starts with a match expression that has just a single clause, that clause can often be rolled into the function signature. E.g. let all_moves s = match s with (a, _) -> ... becomes `let all_moves (a, _) = ...'.
The Array and List modules have more than just fold functions (and alternative standard libraries, such as Core, Batteries, or ExtLib add more functionality to them) that can be used to simplify a lot of Array/List processing.
Example:
let count_ones row =
Array.fold_left (fun c x -> if x=1 then c+1 else c) 0 row
let all_moves (mat, _) =
Array.mapi (fun i row -> (i, count_ones row)) mat
|> Array.to_list |> List.filter (fun (_, c) -> c != 0)
I'm not 100% sure what the intended semantics of countall are, but if I'm understanding it correctly, the following should work (it follows the basic structure of your attempted solution, but relies on mapi instead of fold_left, which is a better fit):
let countall mat k =
Array.mapi (fun i row -> if i = k then 0 else count_ones row) mat
|> Array.fold_left (+) 0
This function can be implemented in different ways, too, e.g.:
let countall mat k =
Array.(append (sub mat 0 k) (sub mat (k+1) (length mat - k - 1)))
|> Array.map count_ones |> Array.fold_left (+) 0
In this variant, I'm using a local open Array.(expr) so that I don't have to prefix every single array operation with Array.. Also, in both versions (+) is a way to write the plus operator as a function with two arguments, and is roughly equivalent to writing (fun x y -> x + y) in its place.
Maybe that could help you
let countall m i =
snd (
Array.fold_left (fun (lg,c) v ->
let c=
if lg = i then c
else
Array.fold_left (fun c xy -> if xy=1 then c+1 else c) c v
in
(lg+1,c)
) (0,0) m
)
;;
Test
# countall c 0;;
- : int = 28
I was given a puzzle as a present. It consists of 4 cubes, arranged side by side. The faces of each cube are one of four colours.
To solve the puzzle, the cubes must be orientated so that all four cubes' tops are different, all their fronts are different, all their backs are different and all their bottom's are different. The left and right sides do not matter.
My pseudo-code solution was:
Create a representation of each
cube.
Get all the possible orientations of
each cube (there are 24 for each).
Get all the possible combinations of
orientations of each cube.
Find the combination of orientations
that satisfies the solution.
I solved the puzzle using an implementation of that pseudo-code in F#, but am not satisifed with the way I did step 3:
let problemSpace =
seq { for c1 in cube1Orientations do
for c2 in cube2Orientations do
for c3 in cube3Orientations do
for c4 in cube4Orientations do
yield [c1; c2; c3; c4] }
The above code is very concrete, and only works out the cartesian product of four sequences of orientations. I started thinking about a way to write it for n sequences of orientations.
I came up with (all the code from now on should execute fine in F# interactive):
// Used to just print the contents of a list.
let print =
Seq.fold (fun s i -> s + i.ToString()) "" >> printfn "%s"
// Computes the product of two sequences - kind of; the 2nd argument is weird.
let product (seq1:'a seq) (seq2:'a seq seq) =
seq { for item1 in seq1 do
for item2 in seq2 do
yield item1 |> Seq.singleton |> Seq.append item2 }
The product function could be used like so...
seq { yield Seq.empty }
|> product [ 'a'; 'b'; 'c' ]
|> product [ 'd'; 'e'; 'f' ]
|> product [ 'h'; 'i'; 'j' ]
|> Seq.iter print
... which lead to ...
let productn (s:seq<#seq<'a>>) =
s |> Seq.fold (fun r s -> r |> product s) (seq { yield Seq.empty })
[ [ 'a'; 'b'; 'c' ]
[ 'd'; 'e'; 'f' ]
[ 'h'; 'i'; 'j' ] ]
|> productn
|> Seq.iter print
This is exactly the usage I want. productn has exactly the signature I want and works.
However, using product involves the nasty line seq { yield Seq.empty }, and it unintuitively takes:
A sequence of values (seq<'a>)
A sequence of sequences of values (seq<seq<'a>>)
The second argument doesn't seem correct.
That strange interface is hidden nicely by productn, but is still nagging me regardless.
Are there any nicer, more intuitive ways to generically compute the cartesian product of n sequences? Are there any built in functions (or combination of) that do this?
Use recursion: the cartesian product of n lists {L1..LN} is the collection of lists you get when you add each element in L1 to each sublist in the cartesian product of lists {L2..LN}.
let rec cart1 LL =
match LL with
| [] -> Seq.singleton []
| L::Ls -> seq {for x in L do for xs in cart1 Ls -> x::xs}
Example:
> cart1 [[1;2];[3;4;5];[6;7]] |> Seq.toList;;
val it : int list list =
[[1; 3; 6]; [1; 3; 7]; [1; 4; 6]; [1; 4; 7]; [1; 5; 6]; [1; 5; 7]; [2; 3; 6];
[2; 3; 7]; [2; 4; 6]; [2; 4; 7]; [2; 5; 6]; [2; 5; 7]]
The cartesian product of [1;2] [3;4;5] and [6;7] is the union of {1 appended to each list in cart [[3;4;5];[6;7]]} and {2 appended to each list in cart [[3;4;5];[6;7]]}. This is the second clause in the match statement.
Here's a solution 'a list list -> Seq<'a list> to calculate the Cartesian product of n lists, with lazy evaluation. I wrote it to be an F# analogue of Python's itertools.product
let product lists =
let folder list state =
state |> Seq.allPairs list |> Seq.map List.Cons
Seq.singleton List.empty |> List.foldBack folder lists
It's based on List.allPairs which was introduced in F# 4.0.
Here's a first try at a list version. I think it could be cleaned up a bit.
let rec cart nll =
let f0 n nll =
match nll with
| [] -> [[n]]
| _ -> List.map (fun nl->n::nl) nll
match nll with
| [] -> []
| h::t -> List.collect (fun n->f0 n (cart t)) h
Hi i have some difficulty in understanding tail-recursivity. I know thats it's important to avoid infinite loops and also for memory usage. I've seen some examples on simple functions like Fibonacci in "Expert in F#", but I don't think i've seen code when the result is something different than just a number.
What would be the accumulator then ? i'm not sure...
Here is a recursive function that I've written. It counts the number of inversions in an array, using the quicksort algorithm. [it's taken from an exercise of the Coursera MOOC Algo I by Stanford]
I'd be grateful if somebody could explain how to make that tail recursive.
[Also, i've translated that code from imperative code, as i had written that in R before, so the style is not functional at all...]
another question: is the syntax correct, A being a (mutable) array, i've written let A = .... everywhere ?
is A <- .... better / the same ?
open System.IO
open System
let X = [|57; 97; 17; 31; 54; 98; 87; 27; 89; 81; 18; 70; 3; 34; 63; 100; 46; 30; 99;
10; 33; 65; 96; 38; 48; 80; 95; 6; 16; 19; 56; 61; 1; 47; 12; 73; 49; 41;
37; 40; 59; 67; 93; 26; 75; 44; 58; 66; 8; 55; 94; 74; 83; 7; 15; 86; 42;
50; 5; 22; 90; 13; 69; 53; 43; 24; 92; 51; 23; 39; 78; 85; 4; 25; 52; 36;
60; 68; 9; 64; 79; 14; 45; 2; 77; 84; 11; 71; 35; 72; 28; 76; 82; 88; 32;
21; 20; 91; 62; 29|]
// not tail recursive. answer = 488
let N = X.Length
let mutable count = 0
let swap (A:int[]) a b =
let tmp = A.[a]
A.[a] <- A.[b]
A.[b] <- tmp
A
let rec quicksortNT (A:int[]) =
let L = A.Length
match L with
| 1 -> A
| 2 -> count <- count + 1
if (A.[0]<A.[1]) then A
else [|A.[1];A.[0]|]
| x -> let p = x
let pval = A.[p-1]
let A = swap A 0 (p-1)
let mutable i = 1
for j in 1 .. (x-1) do
if (A.[j]<pval) then let A = swap A i j
i <- i+1
// end of for loop
// putting back pivot at its right place
let A = swap A 0 (i-1)
let l1 = i-1
let l2 = x-i
if (l1=0) then
let A = Array.append [|A.[0]|] (quicksortNT A.[1..p-1])
count <- count + (l2-1)
A
elif (l2=0) then
let A = Array.append (quicksortNT A.[0..p-2]) [|A.[p-1]|]
count <- count + (l2-1)
A
else
let A = Array.append ( Array.append (quicksortNT A.[0..(i-2)]) [|A.[i-1]|] ) (quicksortNT A.[i..p-1])
count <- count + (l1-1)+(l2-1)
A
let Y = quicksortNT X
for i in 1..N do printfn "%d" Y.[i-1]
printfn "count = %d" count
Console.ReadKey() |> ignore
Thank you very much for your help
As I said in my comment: you do inplace-swapping so it makes no sense to recreate and return arrays.
But as you ask about tail-recursive solutions look at this version using lists and continuation-passing-style to make the algorithm tail-recursive:
let quicksort values =
let rec qsort xs cont =
match xs with
| [] -> cont xs
| (x::xs) ->
let lower = List.filter (fun y -> y <= x) xs
let upper = List.filter (fun y -> y > x) xs
qsort lower (fun lowerSorted ->
qsort upper (fun upperSorted -> cont (lowerSorted # x :: upperSorted)))
qsort values id
remarks:
you can think of it like this:
first partition the input into upper and lower parts
then start with sorting (recursively) the lower part, when you are done with this continue by...
... take lowerSorted and sort the upper part as well and continue with ...
... take both sorted parts, join them and pass them to the outer continuation
the outermost continuation should of course just be the id function
some will argue that this is not quicksort as it does not sort inplace!
maybe it's hard to see but it's tail-recursive as the very last call is to qsort and it's result will be the result of the current call
I used List because the pattern-matching is so much nicer - but you can adopt this to your version with arrays as well
in those cases (as here) where you have multiple recursive calls I always find cont-passing solutions to be easier to write and more natural - but accumulators could be used as well (but it will get messy as you need to pass where you are too)
this will not take less memory than the version without the cont-passing at all - it just will be placed on the heap instead of the stack (you usually have way more heap available ;) ) - so it's a bit like cheating
that's why the imperative algorithm is still way better performance-wise - so a usual compromise is to (for example) copy the array, use the inplace-algorithm on the copy and then return the copy - this way the algorithm behaves as if it's pure on the outside
The whole point to quicksort's swapping partition procedure is that it can mutate the same array; you just pass it the low and the high index of the array's range it has to process.
So make a nested function and pass it just the 2 indices. To make it tail recursive, add the third parameter, list-of-ranges-to-process; when that becomes empty, you're done. Wikibook says you mutate arrays with A.[i] <- A.[j].
A nested function can access its parent function's argument directly, because it is in scope. So, make swap nested too:
let rec quicksort (A:int[]) =
let swap a b =
let tmp = A.[a]
A.[a] <- A.[b]
A.[b] <- tmp
let todo = ... (* empty list *)
let rec partition low high =
.... (* run the swapping loop,
find the two new pairs of indices,
put one into TODO and call *)
partition new_low new_high
let L = A.Length
match L with
| 1 -> (* do nothing A *)
| 2 -> count <- count + 1
if (A.[0]<A.[1]) then (* do nothing A *)
else (* [|A.[1];A.[0]|] *) swap 1 0
| x -> ....
partition 0 L
So partition will be tail recursive, working inside the environment set up for it by quicksort.
(disclaimer: I don't know F# and have never used it, but I know Haskell and Scheme, to some degree).
Update: I can't use any List.function stuff.
I'm new to OCaml and I'm learning this course in which I'm supposed to calculate a list of non decreasing values from a list of values.
So for e.g. I have a list [1; 2; 3; 1; 2; 7; 6]
So function mono that takes in a list returns the following:
# mono [1; 2; 3; 1; 2; 7; 6];;
- : int list = [1; 2; 3; 7]
I do the following:
let rec calculateCheck value lst = (
match lst with
[] -> true
| x :: xs -> (
if (value < x) then
false
else
calculateCheck value xs
)
);;
let rec reverse_list lst = (
match lst with
[] -> []
| x :: xs -> (
reverse_list xs # [x]
)
);;
let shouldReverse = ref 1;;
let cancelReverse somelist lst = (
shouldReverse := 0;
reverse_list lst
);;
let rec mono lst = (
let somelist = ref lst in
if (!shouldReverse = 1) then
somelist := cancelReverse somelist lst
else
somelist := lst;
match !somelist with
[] -> []
| x :: xs -> (
if (calculateCheck x xs) then
[x] # mono xs
else
[] # mono xs
);
);;
Problem?
This only works once because of shouldReverse.
I cannot reverse the value; mono list should return non decreasing list.
Question?
Any easy way to do this?
Specifically how to get a subset of the list. For e.g. for [1; 2; 3; 5; 6], I want [1; 2; 3] as an output for 5 so that I can solve this issue recursively. The other thing, is you can have a list as [1; 2; 3; 5; 6; 5]:: so for the second 5, the output should be [1; 2; 3; 5; 6].
Any ideas?
Thanks
A good way to approach this kind of problem is to force yourself to
formulate what you're looking for formally, in a mathematically
correct way. With some training, this will usually get you
a description that is close to the final program you will write.
We are trying to define a function incr li that contains the
a strictly increasing subsequence of li. As Jeffrey Scoffield asked,
you may be looking for the
longest
such subsequence: this is an interesting and non-trivial algorithmic
problem that is well-studied, but given that you're a beginner
I suppose your teacher is asking for something simpler. Here is my
suggestion of a simpler specification: you are looking for all the
elements that are greater than all the elements before them in the
list.
A good way to produce mathematical definitions that are easy to turn
into algorithms is reasoning by induction: define a property on
natural numbers P(n) in terms of the predecessor P(n-1), or define
a property on a given list in terms of this property on a list of one
less element. Consider you want to define incr [x1; x2; x3; x4]. You
may express it either in terms of incr [x1; x2; x3] and x4, or in
terms of x1 and incr [x2; x3; x4].
incr [x1;x2;x3;x4] is incr[x1;x2;x3], plus x4 if it is bigger
than all the elements before it in the list, or, equivalently, the
biggest element of incr[x1;x2;x3]
incr [x1;x2;x3;x4] is incr[x2;x3;x4] where all the elements
smaller than x1 have been removed (they're not bigger than all
elements before them), and x1 added
These two precise definitions can of course be generalized to lists of
any length, and they give two different ways to write incr.
(* `incr1` defines `incr [x1;x2;x3;x4]` from `incr [x1;x2;x3]`,
keeping as intermediate values `subli` that corresponds to
`incr [x1;x2;x3]` in reverse order, and `biggest` the biggest
value encountered so far. *)
let incr1 li =
let rec incr subli biggest = function
| [] -> List.rev subli
| h::t ->
if h > biggest
then incr (h::subli) h t
else incr subli biggest t
in
match li with
| [] -> []
| h::t -> incr [h] h t
(* `incr2` defines `incr [x1;x2;x3;x4]` from `incr [x2;x3;x4]`; it
needs no additional parameter as this is just a recursive call on
the tail of the input list. *)
let rec incr2 = function
| [] -> []
| h::t ->
(* to go from `incr [x2;x3;x4]` to `incr [x1;x2;x3;x4]`, one
must remove all the elements of `incr [x2;x3;x4]` that are
smaller than `x1`, then add `x1` to it *)
let rec remove = function
| [] -> []
| h'::t ->
if h >= h' then remove t
else h'::t
in h :: remove (incr2 t)