Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function returns list in reverse order in OCaml

Tags:

ocaml

I want to read some numbers from a file, take them to a list and finally display them on the screen. numbers.txt currently has 2 3 5 7 11 however as output i'am getting 11 7 5 3 2 - : unit = ()

Why is this happening?

let rec int_list_from_sb sb n = 
match n with 
| 0 -> [];
| _ -> (bscanf sb " %d" (fun a -> a))::(int_list_from_sb sb (n - 1));;

let file_name = open_in "numbers.txt" in 
let sb = Scanning.from_channel file_name in 
let int_list = int_list_from_sb sb 5 in
List.iter (fun a -> print_int a) int_list;;
like image 246
power_output Avatar asked Apr 20 '16 14:04

power_output


People also ask

What does list Fold_left do in OCaml?

fold_left operates on lists, as your function does, by applying a function and accumulating a result in a particular manner. It takes care of and abstracts the recursion for you.

What does Fold_right do in OCaml?

The function List. fold_right in OCaml “folds” a list to a single element via an operation.


1 Answers

The order of evaluation of arguments is unspecified in OCaml. So when you do f x :: g y, it is unspecified whether f or g gets called first. In your case the recursive call is invoked before the call to bscanf, which is why you get the results in the wrong order.

The general way to fix evaluation-order issues is to put the arguments to a function into local variables when the order of their side effects matters. So instead of f x :: g y, you'd do let fx = f x in fx :: g y if you want the effects of f x to happen before g is called.

However in your case you can just make use of bscanf's continuation argument like this:

bscanf sb " %d" (fun a -> a :: int_list_from_sb sb (n - 1))
like image 51
sepp2k Avatar answered Nov 06 '22 20:11

sepp2k