For learning reasons, I would like to use for loops in OCaml instead of recursion.
I've researched a bit and applied one example of ( https://ocaml.org/learn/tutorials/camlp4_3.10/foreach_tutorial.html ):
let a_list = ["hello"; "world"] in
for s in a_list do
print_endline s
done
This makes sense. However, when I look at it (on Visual Studio, for instance), it tells me that 's' is an int variable. Therefore, I cannot do stuff like (where 'a', 'b',... are variables of any type):
let a_list = [a;b;c...] in
for s in a_list do
match s with
...
done
Is there not a way to use the for statement like in Python? I mean, to use 's in list' and that s's type will be its type and not 'int'?
There is something I do not see there.
Thanks in advance!
There is no foreach in OCaml. Recursion is the idiomatic style, or if you really want to avoid recursion, you can use while
loop. For loop only iterate on integers.
You might be confused on the nature of the tutorial that you are linking: this is a tutorial for implementing a (old style) syntax extension for OCaml, and not a tutorial on using for
loop in OCaml.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.