Reputation: 17253
I am trying to iterate through the characters of string using for loop however I get the following error
let str = "Hello"
for var=0 to (String.length str -1) do
let temp = String.get str var
done;;
Error : Syntax error
I tried this code here
let str = "Hello";;
for i = 0 to (String.length str -1) do
Printf.printf "%s" String.get str i
done;;
and this is the error i get
Error: This expression has type
('a -> 'b -> 'c, out_channel, unit, unit, unit, 'a -> 'b -> 'c)
CamlinternalFormatBasics.fmt
but an expression was expected of type
('a -> 'b -> 'c, out_channel, unit, unit, unit, unit)
CamlinternalFormatBasics.fmt
Type 'a -> 'b -> 'c is not compatible with type unit
Upvotes: 0
Views: 2287
Reputation: 36620
let str = "Hello" for var=0 to (String.length str -1) do let temp = String.get str var done;;
This fails for multiple reasons. The str
binding either needs:
let str = "Hello" in
for var=0 to (String.length str -1) do
let temp = String.get str var
done;;
;;
token to end it as a top-level binding.let str = "Hello";;
for var=0 to (String.length str -1) do
let temp = String.get str var
done;;
let str = "Hello"
let () =
for var=0 to (String.length str -1) do
let temp = String.get str var
done
Your internal binding also doesn't work, because a local binding needs an in
. You then need some expression that uses this value. And bear in mind that String.get
returns a char
rather than string
so use the %c
format specifier.
let str = "Hello"
let () =
for var=0 to (String.length str -1) do
let temp = String.get str var in
Printf.printf "%c" temp
done
As for the following, aside from any of the issues above, this suffers from a precedence issue.
let str = "Hello";; for i = 0 to (String.length str -1) do Printf.printf "%s" String.get str i done;;
Printf.printf "%s" String.get str i
parses as: (Printf.printf) ("%s") (String.get) (str) (i)
.
Clearly you meant for it to parse as below, so simply use those parentheses.
Printf.printf "%c" (String.get str i)
Upvotes: 0
Reputation:
I guess this will work
#let s = "Hello";;
s : string = "Hello"
#for i = 0 to string_length s - 1 do
print_char s.[i]; print_string " "
done;;
o k - : unit = ()
Upvotes: 1