为什么这些显然相同的字符串不相等



我正在尝试以下代码:

open Str
let ss = (Str.first_chars "testing" 3);;
print_endline ("The first 3 chars of 'testing' are: "^ss);;
if (ss == "tes") 
  then print_endline "These are equal to 'tes'" 
  else print_endline "These are NOT equal to 'tes'"

但是,我得到的并不相等:

$ ocaml str.cma testing2.ml
The first 3 chars of 'testing' are: tes
These are NOT equal to 'tes'

为什么Str.first_chars从"测试"不等于" TES"的前3个字符?

另外,我必须使用;;来使此代码起作用(我尝试过的in;的组合无效(。将这3个语句放在一起的最佳方法是什么?

(==(函数是物理相等性运算符。如果要测试两个对象是否具有相同的内容,则应使用具有一个相等符号(=(的结构相等操作员。

将这3个语句放在一起的最佳方法是什么?

OCAML中没有语句。只有表达式,所有返回值。它就像一个数学公式,其中您具有数字,运算符和功能,并且将它们结合在一起成较大的公式,例如sin (2 * pi)。该语句最接近的是具有副作用并返回类型单位值的表达式。但这仍然是表达。

这是一个示例,您可以如何构建表达式,该表达式将首先将返回的子字符串绑定到ss变量,然后按两个表达式计算:无条件打印和条件打印。总之,这将是评估单位值的表达式。

open Str
let () = 
  let ss = Str.first_chars "testing" 3 in
  print_endline ("The first 3 chars of 'testing' are: " ^ ss);
  if ss = "tes" 
  then print_endline "These are equal to 'tes'" 
  else print_endline "These are NOT equal to 'tes'"

这就是它的工作原理

$ ocaml str.cma test.ml 
The first 3 chars of 'testing' are: tes
These are equal to 'tes'

最新更新