使用 OCaml 实现以下内容

发布于 2024-08-03 11:25:15 字数 417 浏览 1 评论 0原文

我正在尝试使用 OCaml 实现以下家庭作业:

g(n) = y if n = x else f(n)

所以,例如

if f(n) = n+1, x = 7, y=42, then g(1) = 2, but g(7) = 42

我有:

# let update f x y = f(x) = y;;
val update : ('a -> 'b) -> 'a -> 'b -> bool = < fun>

但我只是不知道应该使用什么语法才能使其返回函数而不是布尔值。

我并不是要求某人解决问题,但如果有人可以发布一些接受函数、操作它并返回它的代码,我将不胜感激。

I'm trying to implement the following with OCaml for a homework assignment:

g(n) = y if n = x else f(n)

so, for example

if f(n) = n+1, x = 7, y=42, then g(1) = 2, but g(7) = 42

I've got:

# let update f x y = f(x) = y;;
val update : ('a -> 'b) -> 'a -> 'b -> bool = < fun>

but I just don't know the syntax I should use in order to make it return a function instead of a boolean value.

I'm not asking for someone to solve the problem, but if someone could post some code that takes in a function, manipulates it, and returns it, I'd appreciate it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年少掌心 2024-08-10 11:25:15

不确定我是否理解你的作业——你确定你只是不想调用 f(n) 而不是返回它吗?

但是,一些示例 - 返回另一个函数的函数

(* given a number, return a function that takes an int 
   and returns integer + number *)
let adder n = 
    let f x = n+x in
    f

请注意,它返回的类型是一个函数:

# adder 10;;
- : int -> int = <fun>
# let g = adder 10;;
val g : int -> int = <fun>
# g 20;;
- : int = 30

基本上,要返回一个函数,您可以定义该函数并返回它。

假设您想要接受一个函数并返回一个返回双倍值的函数:

let doubler f = 
    let g x = 2 * (f x) in 
    g

# let f x = x + 1;;
val f : int -> int = <fun>
# let g = doubler f;;
val g : int -> int = <fun>
# g 10;;
- : int = 22

Not sure I understand your homework -- are you sure you just don't want to call f(n) instead of returning it?

But, some examples -- a function that returns another function

(* given a number, return a function that takes an int 
   and returns integer + number *)
let adder n = 
    let f x = n+x in
    f

Note that the type it returns is a function:

# adder 10;;
- : int -> int = <fun>
# let g = adder 10;;
val g : int -> int = <fun>
# g 20;;
- : int = 30

Basically, to return a function, you define the function and just return it.

Let's say you want to take a function and return a function that returns double the value:

let doubler f = 
    let g x = 2 * (f x) in 
    g

# let f x = x + 1;;
val f : int -> int = <fun>
# let g = doubler f;;
val g : int -> int = <fun>
# g 10;;
- : int = 22
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文