If statement Ocaml if-then-else语法错误
为什么这个Ocaml语句会给我一个语法错误If statement Ocaml if-then-else语法错误,if-statement,ocaml,ocamllex,If Statement,Ocaml,Ocamllex,为什么这个Ocaml语句会给我一个语法错误 let a = 0;; if a = 0 then let b = 0;; if-then-else语句是否总是必须返回值 编辑:这是我正在努力解决的代码。我想用map函数在列表上应用这个函数。函数应该查看列表wordlist中的每个单词,并将其添加到stringmap中。如果已将其添加到字符串映射中,则在其密码中添加1 module StringMap = Map.Make(String) let wordcount = StringMap.emp
let a = 0;; if a = 0 then let b = 0;;
if-then-else语句是否总是必须返回值
编辑:这是我正在努力解决的代码。我想用map函数在列表上应用这个函数。函数应该查看列表wordlist中的每个单词,并将其添加到stringmap中。如果已将其添加到字符串映射中,则在其密码中添加1
module StringMap = Map.Make(String)
let wordcount = StringMap.empty
let findword testword =
let wordcount = (if (StringMap.mem testword wordcount)
then (StringMap.add testword ((StringMap.find testword wordcount)+1) wordcount)
else (StringMap.add testword 1 wordcount))
List.map findword wordlist
如果then表达式的计算结果为unit
()
,则只能使用if-then
而不使用else
,否则表达式将不会进行类型检查。如果没有else,if相当于编写if x then y else()
,它只能在y为单位时进行类型检查
看看这个,看看有没有什么好消息
(术语说明:OCaml中没有语句,因为所有内容都是一个表达式,所以术语“if statement”不太适用。我仍然理解您的意思,但我认为这是值得注意的)是的,
if
是OCaml中的表达式,而不是语句。最好的方法是在OCaml中没有语句。一切都是一种表达。(无可否认,有些表达式返回的是类似于语句的()
)
如果e
的类型是unit
(即,如果它返回()
),则只能使用如果b那么e
还要注意的是,除了在模块的顶层,您不能只说
让v=e
。在顶层,它在模块中定义了一个全局名称。在其他情况下,您需要在e2中说让v=e1
;let
定义了一个本地符号v
,用于表达式e2
对let b=
问题的一个答案-其工作原理如下:
let a = 0
let b = if a = 0 then 0 else 1
(* or whatever value you need in the else branch *)
然后是地图问题:手册上说地图是可应用的——这意味着Stringmap.add返回一个新地图。您必须使用ref来存储地图-请参阅以下ocaml顶级协议:
# module StringMap = Map.Make(String);;
# let mymap = ref StringMap.empty ;;
val mymap : '_a StringMap.t ref = {contents = <abstr>}
# mymap := StringMap.add "high" 1 !mymap;;
- : unit = ()
# StringMap.mem "high" !mymap;;
- : bool = true
# StringMap.mem "nono" !mymap;;
- : bool = false
# StringMap.find "high" !mymap;;
- : int = 1
# StringMap.find "nono" !mymap;;
Exception: Not_found.
#模块StringMap=Map.Make(String);;
#让mymap=ref-StringMap.empty;;
val mymap:'_astringmap.t ref={contents=}
#mymap:=StringMap.add“high”1!我的地图;;
-:单位=()
#StringMap.mem“高”!我的地图;;
-:bool=true
#StringMap.mem“nono”!我的地图;;
-:bool=false
#StringMap.find“high”!我的地图;;
-:int=1
#StringMap.find“nono”!我的地图;;
异常:未找到。
那么答案是不能这样做的,因为“let b=0”不是一个表达式吗?let b=0
除了在模块的顶层之外,在语法上是无效的。你需要说让b=0进入…
;i、 例如,它定义了在子表达式中使用的局部符号b。