Getting nth element from a list of floats - ocaml

If I have a list of floats:
let float_list = [1.5,2.5,3.5]
I'm looking to extract a number from this list similar to:
List.nth float_list 2
However what is returned is type float * float and not 3.5. List.nth only seems to return integers from an integer list and I can't seem to find a function in https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html to return the nth element of any list other than an integer list.
Would anyone be able to help with this?

Your float_list isn't a list of floats, it's a list of float * float * float tuples and it only contains one such tuple. So in addition to not having the type you want, List.nth float_list 2 will actually cause an exception at run time because 2 is not a valid index for that list.
You want [1.5; 2.5; 3.5], which is actually a list of floats. With that list List.nth will work exactly as you want.

List literals in OCaml use ; to separate items. , is used to separate items in tuples. So the type of float_list is actually (float * float * float) list, and it contains only a single element.

Related

Return a list of the odd indices using List.map

If I have a list [1;2;3;4;5;6] and I want to return a list of the odd indices [2;4;6], could I do this with List.map and some function? I'm having difficulty figuring this out.
What List.map does is return a function (call it f say) of each of the elements of the list. For each element x of the input list, it returns f x in the resulting list. Hence, the returned list is always the same length as the one it is passed.
Since you want a shorter list, you can't use List.map.
As #UnholySheep says, you could use List.filteri. It's specifically intended for returning only some of the elements of the list based on their position in the list.

How to count the number of consecutive occurrences in a list of any element type in OCaml?

In OCaml, suppose I have a string list as follows:
let ls : string list = ["A"; "A"; "B"; "B"; "A"; "Y"; "Y"; "Y"] ;;
I'm having trouble writing a function that calculates how many times an element occurs consecutively and also pairs up that element with its frequency. For instance, given the above list as input, the function should return [("A", 2); ("B", 2), ("A", 1), ("Y", 3)].
I've tried looking for some hints elsewhere but almost all other similar operations are done using int lists, where it is easy to simply add numbers up. But here, we cannot add strings.
My intuition was to use something like fold_left in some similar fashion as below:
let lis : int list = [1;2;3;4;5]
let count (lis : int list) = List.fold_left (fun x y -> x + y) (0) (lis)
which is essentially summing all the elements cumulatively from left to right. But, in my case, I don't want to cumulatively sum all the elements, I just need to count how many times an element occurs consecutively. Some advice would be appreciated!
This is obviously a homework assignment, so I will just give a couple of hints.
When you get your code working, it won't be adding strings (or any other type) together. It will be adding ints together. So you might want to look back at those examples on the net again :-)
You can definitely use fold_left to get an answer. First, note that the resultl is a list of pairs. The first element of each pair can be any type, depending on the type of the original list. The second element in each pair is an int. So you have a basic type that you're working with: ('a * int) list.
Imagine that you have a way to "increment" such a list:
let increment (list: ('a * int) list) value =
(* This is one way to think of your problem *)
This function looks for the pair in the list whose first element is equal to value. If it finds it, it returns a new list where the associated int is one larger than before. If it doesn't find it, it returns a new list with an extra element (value, 1).
This is the basic operation you want to fold over your list, rather than the + operation of your example code.

Ocaml - Checking that all rows of a matrix are the same length

i'm trying to find a way in ocaml to apply functions to matrices.
In my implementation, a matrix is an int list of an int list (as in the matrix is a int list, which holds other int lists)
My idea right now is:
let valid_matrix x =
match x with
[] -> true
| (map length x) ->
;;
(Map and length are separate functions which find the number of elements in a list and perform a map function in which a function is applied to all elements of a list, i cannot use a library).
I know this code is incomplete but i am unsure how to compare the number of elements in each matrix to each other and I don't know either how I would access each individual int list (row) within the matrix if I wanted to do further manipulation to it.
Kind regards.
"i cannot use a library" => so this is homework. No code for you, just hints.
Split your problem in two:
1) Change the rows of the matrix into their length. For this apply the length function to each row of the matrix (your map function). This then gives you a int list containing the length of each row.
2) Check that all values in the list are the same.

Creating a list of strings with varying subscripts

I want to define a function which takes input a value m and returns a vector C=['c1','c2',...,'cm']. How do I vary the subscript or the index of the strings inside the list?
This should work:
def makeList(m):
return ['c' + str(x+1) for x in xrange(m)]
newList = makeList(5)
print(newList)
The function takes an argument m and uses a list comprehension to build a list of strings with length m. You could of course change 'c' to any other string you want to prepend to the integer.

How to print a certain element in each list

I'm coding in haskell and want to know how find a certain element in mutiple list.
Here an example let say:
x = [(1,2,3,4,5),
(3,4,5,6,6),
(5,6,2,1,1),
(1,2,5,6,2)];
Let say I want to find the 3rd element of each list.
So the program will print out 4,6,1,6
I know about the !! but when I do something like x !! 3, it prints out the third row(1,2,5,6,2).
I want it so it print out the 3rd element of each list.
What you've provided is not actually a list of lists, but a list of tuples. Tuples have a special type based on the number and type of their elements, so the type of your x above is [(Int,Int,Int,Int,Int)].
Unlike lists, which allow us to extract values by index with the !! operator (ex. [1,2,3] !! 1 = 2), in order to extract specific values from a tuple we must pattern match the entire tuple, giving some name to the value we wish to extract and using it in our return value. To extract the fourth value from a tuple of holding 5 values, we could write a function like this:
f (a,b,c,d,e) = d
Or, as an anonymous function (because, if we are only going to use it when mapping over the list, it's nice to not bother assigning it a name):
(\(a,b,c,d,e) -> d)
Since we only care about the fourth value, we can choose to discard all others (you said third but meant index 3 -> 4th term above?):
(\(_,_,_,x,_) -> x)
Now we have a list of such tuples, and we'll want to apply it to each. We can do this with map, which will apply the function to each and return a list of the third value from each tuple:
f xs = map (\(_,_,_,x,_) -> x) xs
Or, with eta-reduction:
f = map (\(_,_,_,x,_) -> x)
Example usage:
gchi>> f [(1,2,3,4,5),(3,4,5,6,6),(5,6,2,1,1),(1,2,5,6,2)]
[4,6,1,6]