简体   繁体   中英

How to let OCaml function returns a tuple containing a string and a function?

Eventually what I want is what x represents: let x = (something, (myfunc1 para1));; so that when calling x , I get a tuple, but when calling (snd x) para , I will get a return value of myfunc1 para .

What I'm trying is like this:

let myfunc2 para1 para2 = 
  let myfunc1 para2 = ... in
  ( (fst para1), (myfunc1 para2) );;

And I want to call myfunc2 like this: let x = myfunc2 para1 to get what I described above. However, what I get is just a function which when called with para1 will return a regular tuple, not a (something, function) tuple

You have a useless para2 parameter in your definition. The correct way is:

let myfunc2 para1 = 
  let x = ... in
  let myfunc1 para2 = ... in
  ( x, myfunc1 );;

But it would help if we could speak about a concrete example. You are misunderstanding something obvious, but I do not know what.

Here is a concrete example. Suppose we want a function f which accepts a number n and returns a pair (m, g) where m is the square of n and g is a function which adds n to its argument:

let f n =
  let m = n * n in
  let g k = n + k in
    (m, g)

Or shorter:

let f n = (n * n, fun k => n + k)

Now to use this, we can do:

let x = f 10 ;;
fst x ;; (* gives 100 *)
snd x ;; (* gives <fun> *)
snd x 5 ;; (* gives 15, and is the same thing as (snd x) 5 *)

Now let us consider the following bad solution in which we make the kind of mistake you have made:

let f_bad n k =
  let m = n * n in
  let g k = n + k in
    (m, g k)

Now f_bad wants two arguments. If we give it just one, we will not get a pair but a function expecting the other argument. And when we give it that argument, it will return a pair of two integers because (m, gk) means "make a pair whose first component is the integer m and the second component is g applied to k , so that is an integer, too."

Another point worth making is that you are confusing yourself by calling two different things para2 . In our definition of f_bad we also confuse ourselves by calling two different things k . The k appearing in the definition of g is not the same as the other k . It is better to call the two k 's different things:

let f_bad n k1 =
  let m = n * n in
  let g k2 = n + k2 in
    (m, g k1)

Now, does that help clear up the confusion?

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