简体   繁体   中英

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:

let fun x = String.length x;;

But it's showing syntax error. Why? If I just write String.length x;; it's fine but what's wrong in my function declaration?

How to pass string variable as argument to function in OCaml?

fun is a reserved keyword in OCaml. You can choose another name that's not a keyword and the function will work. Here's a list of reserved keywords in OCaml: https://caml.inria.fr/pub/docs/manual-ocaml/manual071.html

You are mixing different syntaxes here:

  1. LET <ident> <ident>* = <expr>
  2. FUN <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. It's a keyword and not an identifyer so the syntax parser gives you an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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