Finding the longest run of positive integers in OCaml - ocaml

Trying an OCaml question of iterating through the list and finding the longest run of positive or negative integers. My thinking so far is you have to use List.fold_left and somehow +1 to the accumulator each time the next sign is the same as the current sign. However, I'm a bit stuck on how to save that value. Any help would be appreciated.

I suspect you're being downvoted because this is the kind of basic question that's probably best answered by looking at an introduction to OCaml or functional programming in general.
The essential idea of folds in general and List.fold_left in particular is to maintain some state while traversing a collection (or a list in particular). When you say you want to "save" a value, the natural answer is that the value would be part of the state that you maintain while traversing the list.
The template for calling List.fold_left looks like this:
let final_state =
List.fold_left update_function initial_state list
The update function takes the current state and the next element of the list, and returns the value of the next state. So it looks like this:
let update_function old_state list_element =
let new_state =
(* compute based on old state and element *)
in
new_state
So the explicit answer to your question is that your update function (the function that you "fold" over the list) would save a value by returning it as part of the new state.
Here's some code that returns the largest non-negative integer that it sees in a list:
let largest_int list =
let update largest_so_far element =
max largest_so_far element
in
List.fold_left update 0 list
This code "saves" the largest int seen so far by returning it as the value of the update function. (Note that it returns a value of 0 for an empty list.)

Ah dang im also up all night doing OCaml LOL!!!
here's my shot at it ... one way is to sort the list and then find the first positive or first negative depending on how you sort ... checkout sort function from https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html ... then it's easy to get the size.
Let's say you don't want to use this built in library ... This code should be close to working (If my editor/debugger worked with OCaml I'd further test but I think this is close to good)
let mostPositives(l: int list) : int list=
let counter = ref 0 in
let maxSize = ref 0 in
for i = 0 to List.length(l) -1 do
if (List.nth l i) >= 0 then
counter := !counter + 1
else
counter := 1;
maxSize := (max !counter !maxSize );
done;

Related

How to generate a list of natural numbers from 1....n?

I am currently trying to, inside my function, generate a list. The user will pass in one parameter, which will be an Int. The function's job is to generate a list, starting from 1, and going up to n. So the list would look something like
[1....n]
What I have done thus far is this:
iterate (+1) 1
While this provides the correct pattern, it goes on forever. How would I be able to stop at n? In addition, how would I be able to append '1' at the end of the list, as such:
[1...n,1]
It's literally as simple as:
f :: Int -> [Int]
f n = [1..n] ++ [1]

ocaml remove duplicates in a list

Hey guys I am having a bit of trouble i have a general idea what the code should be but not to sure what to do from here.
The question is: Define a function remove_elts taking a list of items as well as a list of items to
remove from the first list, and returning a list with all occurrences of the items
to be removed gone.
My code is :
let remove_elts l reml =
match l with
[] -> false
| hd :: tl -> if hd = l then reml
else hd :: remove_elts l tl;;
Any filtering function, i.e., a function that takes a container and returns another container that contains elements of the input container that satisfy some property, is implemented using the following algorithm:
output-sequence = []
foreach element in the input-sequeunce:
if element satisfies condition:
output-sequence := output-sequence + element
This iteration has two elements which differ with each step, the element variable that takes in order the elements of the input-sequence and the output-sequence that grows every time, the <element> satisfies the condition.
In functional programming, iteration is commonly represented with recursion which is more natural from the mathematical point of view. Anything that changes in the iteration will become a parameter of the recursive function, and each step is represented as a recursive call with the new values of the variables. So the same iteration in the functional style (pseudocode)
filter input-sequence output-sequence =
if is-empty input-sequence then output-sequence
else
let element = first-element-of input-sequence in
let rest = drop-first-element input-sequence in
if element satisfies condition
then filter rest (output-sequence + element)
else filter rest output-sequence
And the iteration is called as
filter input-sequence []
So it is a little bit more verbose then the foreach but this is because foreach is basically a syntactic sugar.
Now, your task is to implement this in OCaml, keeping in mind two things:
1) In OCaml you can use pattern matching, instead of is-empty,first-element-of, and drop-first-element primitives.
2) You're using a singly-linked list as the sequence, so appending an element to the end of it is very expensive, it is O(N) (as you have to go through all elements, until you reach the end), and doing this in cycle will make your algorithm O(N^2), so instead you should prepend to the beginning (which is O(1)) and at the end of recursion, reverse the list.

generate all binary trees with n nodes OCaml

I am trying to write a code that generates all binary trees with n nodes (so the program has to return a list in which we can find all the different binary trees with n nodes).
Here is the way I represent binary trees :
type 'a tree = Empty | Node of 'a * 'a tree * 'a tree
So I am trying to implement a function all_tree : int -> tree list such that :
all_tree 0 = [Empty]
all_tree 1 = [Node('x',Empty,Empty)]
all_tree 2 = [Node('x',Node('x',Empty,Empty),Empty); Node('x',Empty,Node('x',Empty,Empty))]
...
I tried several ideas but it didn't work out. For example we could try the following :
let rec all_tree result = function
|0 -> r
|s -> all_tree ((List.map (fun i -> Node('x',i,Empty)) result)#(List.map (fun i -> Node('x',Empty,i)) result) ) (s-1)
in all_tree [Empty] (*some number*)
This code doesn't work because it doesn't generate every possibility.
Here is one possible answer.
let rec all_trees = function
| 0 -> [Empty]
| n ->
let result = ref [] in
for i = 0 to n-1 do
let left_side = all_trees i
and right_side = all_trees (n-1-i) in
List.iter
(fun left_tree ->
List.iter
(fun right_tree ->
result := (Node('x', left_tree, right_tree)) :: (!result)
)
right_side
)
left_side
done;
!result
;;
It's pretty simple: a tree with n>0 nodes is a tree with 1 node at the top, and then n-1 nodes below split between a certain number on the left and a certain number on the right. So we loop for i from 0 to n-1 through all possible numbers of values on the left side, and n-i-1 is going to be the number of nodes on the right side. We recursively call all_trees to get the trees with i and n-i-1 nodes, and simply aggregate them.
Notice that it's a very poor implementation. It has everything a recursive function should avoid. See something like this page on recursive implementations of the Fibonacci sequence to see how to improve it (one of the first things to do would be to cache the results rather than recompute the same things many many times).
I do agree with the question's comments though that writing a printer would be step 1 in that kind of project, because it's really annoying having to read through messy things like [Node ('x', Node ('x', Empty, Node ('x', Node ('x', Empty, Empty), Empty)), Empty);. Naming variables better would also make it easier for people to read your code and will increase the chance someone will help you. And generally, listening to the comments when people give you advice on how to properly ask your questions will make it easier for you to get answers both right now and in your future questions. For instance, in my own code, I used i as the loop index. It makes sense to me while I'm coding it, but when you read the code, maybe you would have preferred to read something like left_side_nodes or something like that, which would have made it obvious what this variable was supposed to do. It's the same in your own scenario: you could call i something like subtree or maybe something even more explicit. Actually, properly naming it could make you realize what's wrong with your code. Often, if you can't properly name a variable, it's that you don't really understand what it's doing (even local variables).

Asking about ML recursive function

I have been doing with ml function and got some annoying things.
I will explain it with simple code.
For example if there is a list(int*int) and I want to examine that there are some tuples that contains 3 for the first element.
L = [(1,2),(2,3),(3,5),(3,4)]
so in this list, I want to get 5 and 4.
However, in ML, the function is recursive, so if I write code like this.
fun a(list) =
if #1(hd(list)) = 3 then #2(hd(list))
else a(tl(list))
in this simple function, it can get 5 but not 4 because once it detects that (3,5) is satisfied the condition it returns 5 and the function finishes.
Is there any way to get the 4 as well?
I don't know ml but basically instead of doing else you need to do this:
fun a(list) =
if list = nil then nil
else
if #1(hd(list)) = 3
then
#2(hd(list)) :: a(tl(list))
else
a(tl(list))
(I am gradually editing this response as I learn more about ML :)
You forgot to call the function recursively on the tail of the list where the condition held.
In ML, you almost never use hd and tl but use pattern matching instead. And you can pattern-match on tuples for more readability:
fun filter [] = []
| filter ((x, y)::xys) = if x = 3
then y::(filter xys)
else filter xys
And high-order functions on List structure is another option in case you would like to use them.

Erlang Iterating through list removing one element

I have the following erlang code:
lists:all(fun(Element) -> somefunction(TestCase -- [Element]) end, TestCase).
Where TestCase is an array. I'm trying to iterate over the list/array with one element missing.
The problem is this code takes O(N^2) time worst case because of the copies of the TestCase array everytime -- is called. There is a clear O(N) Solution in a non functional language.
saved = TestCase[0]
temp = 0
NewTestCase = TestCase[1:]
for a in range(length(NewTestCase)):
somefunction(NewTestCase)
temp = NewTestCase[a]
NewTestCase[a] = saved
saved = temp
... or something like that.
Is there an O(N) solution in erlang?
Of course there is, but it's a little bit more complicated. I am assuming that some_function/1 is indeed a boolean function and you want to test whether it returns true for every sub-list.
test_on_all_but_one([], _Acc) -> true;
test_on_all_but_one([E|Rest], Acc) ->
case somefunction(lists:reverse(Acc,Rest)) of
true -> test_on_all_but_one(Rest, [E|Acc]);
false -> false
end.
This implementation is still O(length(List)^2) as the lists:reverse/2 call will still need O(length(Acc)). If you can modify somefunction/1 to do it's calculation on a list split into two parts, then you can modify the previous call to somefunction(lists:reverse(Acc,Rest)) with somefunction(Acc, Rest) or something similar and avoid the reconstruction.
The modification depends on the inner workings of somefunction/1. If you want more help with that, give some code!
You can split the list into 2 sublists, if it's acceptable of course.
witerate(Fun, [Tail], Acc) ->
Fun([], Acc);
witerate(Fun, [Head | Tail], Acc) ->
Fun(Tail, Acc),
witerate(Fun, Tail, [Head | Acc]).