Returns a list of functions in reverse order in OCaml

I want to read some numbers from a file, put them in a list, and finally display them on the screen. number.txt currently has 2 3 5 7 11 , however, as the output i'am gets 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;; 
+5
source share
1 answer

The order in which the arguments are evaluated is not specified in OCaml. Therefore, when you execute fx :: gy , it is not fx :: gy whether the call to f or g first. In your case, the recursive call is called before the bscanf call, so you get the results in the wrong order.

A common way to troubleshoot evaluation problems is to put function arguments in local variables when the order of their side effects matters. Therefore, instead of fx :: gy you should do let fx = fx in fx :: gy if you want fx effects to be executed before g called.

However, in your case, you can simply use the bscanf continuation bscanf as follows:

 bscanf sb " %d" (fun a -> a :: int_list_from_sb sb (n - 1)) 
+5
source

Source: https://habr.com/ru/post/1247529/


All Articles