是“动态的” OCaml 中可以进行模式匹配吗?

发布于 2024-12-29 18:42:49 字数 201 浏览 2 评论 0 原文

那么在 Ocaml 中你可以在编译时做到这一点:

let handle item = match item with
   | 1 -> "Do this";
   | 2 -> "Do that";
   | n -> "Do Nothing";
;;

有没有办法在运行时实现它?就像某种责任链模式?

Well in Ocaml you can do this at compile-time :

let handle item = match item with
   | 1 -> "Do this";
   | 2 -> "Do that";
   | n -> "Do Nothing";
;;

Is there a way to realize it at runtime ? Like some kind of chain of responsibility pattern ?

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

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

发布评论

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

评论(1

空气里的味道 2025-01-05 18:42:49

是的,有这样的模式。

假设您正在处理一个必须接受整数并返回字符串的函数,并且默认情况下它将为每个整数返回“Do Nothing”

let func : (int -> string) ref = ref (fun _ -> "Do nothing") 

let _ = (!func) 1
- : string = "Do nothing"

如果您想说,你可以这样做:

let () = 
  let old = !func in 
  func := (function 1 -> "Do this" | n -> old n)

let _ = (!func) 1
- : string = "Do this"

Yes, there is such a pattern.

Let's assume that you're dealing with a function that must accept an integer and return a string, and that by default it will return "Do nothing" for every integer :

let func : (int -> string) ref = ref (fun _ -> "Do nothing") 

let _ = (!func) 1
- : string = "Do nothing"

If you wish to say that "Do this" should be returned when the argument is 1, you can do:

let () = 
  let old = !func in 
  func := (function 1 -> "Do this" | n -> old n)

let _ = (!func) 1
- : string = "Do this"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文