Ocaml,将所有指定的元素替换为列表中的给定元素 [英] Ocaml, replace all specified elements with a given element in a list
问题描述
我正在写一个ocaml项目,其中有一个函数用'E'
替换字符列表中的所有''
.这是我的建议代码:
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)
;;
但是仍然存在语法错误...(在线|(h :: t)-> .... char 18-21)
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!
推荐答案
这是第一个错误所在:[] -> let a ='E'; a::[]
如果要在声明后使用a,则应改写[] -> let a = 'E' in a ::[]
.显然,[] -> ['E']
更简单.
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.
第二个是在模式匹配中使用if
.您应该改用when
:|(h::t) when h = '' -> 'E'::(string_lst_change_E t)
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)
这篇关于Ocaml,将所有指定的元素替换为列表中的给定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!