I am writing a ocaml project, in which I have a function that replace all ''
in a char-list with 'E'
. Here's my code for this propose:
let rec string_lst_change_E lst =
match lst with
[] -> let a ='E'; a::[]
|(h::t) if (h = '') -> 'E'::(string_lst_change_E t)
|(h::t) -> h::(string_lst_change_E t)
;;
It says I have a syntax error... But I cannot figure out by myself.
I tried to modify it like this:
let rec string_lst_change_E lst =
match lst with
[] -> 'E'::[]
|(h::t) ->if (h = '') then 'E'::(string_lst_change_E t) else h::(string_lst_change_E t)
;;
but still there's syntax error...(on the line |(h::t) -> .... char 18-21)
Please help me to take a look at it. Thank you!
This is where the first error lies: [] -> let a ='E'; a::[]
If you want to use a after declaring it, you should instead write [] -> let a = 'E' in a ::[]
. Obviously, [] -> ['E']
is simpler.
The second is the use of if
in a pattern match. You should use when
instead: |(h::t) when h = '' -> 'E'::(string_lst_change_E t)
But what's '' anyway? The empty character? How would you get this in a string? Typing ''
is itself a syntax error. Try it in the toplevel! To make your code compile, I replaced ''
by ' '
.
let rec string_lst_change_E lst =
match lst with
| [] -> let a ='E' in a::[]
| (h::t) when h = ' ' -> 'E'::(string_lst_change_E t)
| (h::t) -> h::(string_lst_change_E t)
Note that you can simply use function here:
let rec string_lst_change_E = function
| [] -> let a ='E' in a::[]
| (h::t) when h = ' ' -> 'E'::(string_lst_change_E t)
| (h::t) -> h::(string_lst_change_E t)