Last active
February 14, 2018 01:40
-
-
Save bramford/648770b73074fd2768a428ce097bae9a to your computer and use it in GitHub Desktop.
OCaml increment tuples recursively in order and add to list - Compiler error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
I am attempting to create a 2d 'map' for a simple ncurses game. | |
The map should consist of a list of coordinates (tuples of int * int) | |
For example: [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2);] | |
would be the list that represents all coordinates in the 3x3 'map': | |
2### | |
y1### | |
0### | |
012 | |
x | |
To create this list of coordinates, I wrote a function that takes | |
the minimum and maximum values for both x and y in addition to a | |
list to be populated with the resulting values. | |
See code and comments below | |
*) | |
(* Example output list of tuples *) | |
let list_of_incremented_tuples = [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2);] | |
(* Recursive function that now works *) | |
let rec add_incremented_tuples_to_list x x_max y y_max l = | |
let l = if y <= y_max then | |
add_incremented_tuples_to_list x x_max (y + 1) y_max ((x, y) :: l) | |
else l in | |
let l = if x <= x_max then | |
add_incremented_tuples_to_list (x + 1) x_max y y_max ((x, y) :: l) | |
else l in | |
l | |
(* Example execution *) | |
let list_of_incremented_tuples = add_incremented_tuples_to_list 0 2 0 2 [] | |
(* val list_of_incremented_tuples : (int * int) list = | |
[(3, 2); (3, 1); (3, 0); (2, 0); (3, 2); (3, 1); (2, 1); (3, 2); (2, 2); | |
(2, 3); (2, 2); (2, 1); (2, 0); (1, 0); (3, 2); (3, 1); (2, 1); (3, 2); | |
(2, 2); (2, 3); (2, 2); (2, 1); (1, 1); (3, 2); (2, 2); (2, 3); (2, 2); | |
(1, 2); (2, 3); (1, 3); (1, 2); (1, 1); (1, 0); (0, 0); (3, 2); (3, 1); | |
(2, 1); (3, 2); (2, 2); (2, 3); (2, 2); (2, 1); (1, 1); (3, 2); (2, 2); | |
(2, 3); (2, 2); (1, 2); (2, 3); (1, 3); (1, 2); (1, 1); (0, 1); (3, 2); | |
(2, 2); (2, 3); (2, 2); (1, 2); (2, 3); (1, 3); (1, 2); (0, 2); (2, 3); | |
(1, 3); (0, 3); (0, 2); (0, 1); (0, 0)] *) | |
(* Imperative attempt also failed. I haven't looked further in to this as | |
I don't intend on using 'for' and would prefer a recursive function *) | |
let add_incremented_tuples_to_list x x_max y y_max l = | |
for x = x to x_max do | |
for y = x to y_max do | |
let l = ((x, y) :: l) | |
done | |
done | |
l | |
let list_of_incremented_tuples = add_incremented_tuples_to_list 0 2 0 2 [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment