简体   繁体   English

如何在 OCaml 的 function 中将字符串变量作为 arguments 传递?

[英]How to pass string variables as arguments in function in OCaml?

I wrote a simple code for a function which takes a string and return its length:我为 function 写了一个简单的代码,它接受一个字符串并返回它的长度:

let fun x = String.length x;;

But it's showing syntax error.但它显示语法错误。 Why?为什么? If I just write String.length x;;如果我只写String.length x;; it's fine but what's wrong in my function declaration?没关系,但是我的 function 声明有什么问题?

How to pass string variable as argument to function in OCaml?如何将字符串变量作为参数传递给 OCaml 中的 function?

fun is a reserved keyword in OCaml. fun是 OCaml 中的保留关键字。 You can choose another name that's not a keyword and the function will work.您可以选择另一个不是关键字的名称,function 将起作用。 Here's a list of reserved keywords in OCaml: https://caml.inria.fr/pub/docs/manual-ocaml/manual071.html以下是 OCaml 中的保留关键字列表: https://caml.inria.fr/pub/docs/manual-ocaml/manual071.html

You are mixing different syntaxes here:您在这里混合了不同的语法:

  1. LET <ident> <ident>* = <expr>让 <ident> <ident>* = <expr>
  2. FUN <ident>* -> <expr>有趣的 <ident>* -> <expr>

The "let" must be followed by the name of the function you want to create and "fun", being a reserved keyword, is not a valid name for the function. “let”后面必须跟您要创建的 function 的名称,而作为保留关键字的“fun”不是 function 的有效名称。 It's a keyword and not an identifyer so the syntax parser gives you an error.它是关键字而不是标识符,因此语法解析器会给您一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM