解决缺乏“提升”的问题在 Clojure 中

发布于 2024-10-27 19:57:17 字数 319 浏览 6 评论 0原文

我有几次发现我有一组相互关联的函数,而我自然地将它们放入文件中的方式最终会与它们的依赖项发生冲突(即函数 1 依赖于函数 2,但位于函数 1 之上)。当我编写代码时,我通常会不断评估顶级表达式,并且只会评估整个文件以刷新对引用或其他内容的依赖关系。我经常发现,我最终会遇到依赖冲突,并且最终不得不处理一堆函数。

在我知道的其他语言中,一旦你声明了一个函数,它就会被“提升”到幕后,就好像它出现在其他任何东西之前一样。这样您就不必担心代码中的顺序,并且可以将函数视为模块化代码。正是由于缺乏这个功能,clojure 一直困扰着我。我做错了什么吗?这只是一个小烦恼,而不是一个大问题,这是你刚刚习惯关注的事情吗?

I have found a few times that I have a group of inter-related functions, and how I would naturally place them in the file ends up conflicting with their dependencies (i.e function 1 depends on function 2, but is above function 1). When I am writing code, I usually keep evaluating top level expressions, and will only evaluate the whole file to refresh dependencies on refs or whatnot. I am finding that quite frequently, I end up with a dependency conflict, and end up having to juggle a bunch of functions around.

In other languages I know, as soon as you declare a function, it gets "hoisted" behind the scenes as if it appeared before anything else. That way you dont need to worry about the order of things in your code, and can treat functions as modular bits of code. It is the lack of this feature that keeps biting me in clojure. Am I doing something wrong? Its more a minor annoyance then a huge deal, is this something you just sort of get used to paying attention to?

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

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

发布评论

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

评论(1

诺曦 2024-11-03 19:57:17

声明很好地解决了这个问题,

declare
macro
Usage: (declare & names)
defs the supplied var names with no bindings, useful for making forward declarations.
Added in Clojure version 1.0

您可以通过在命名空间的开头添加声明语句来避免混淆函数顺序

(declare fun1 fun2 fun3)

(defn fun3 [] (fun1))
(defn fun1 [] (fun2))
(defn fun2 [] 42)

declare solves this problem nicely

declare
macro
Usage: (declare & names)
defs the supplied var names with no bindings, useful for making forward declarations.
Added in Clojure version 1.0

you can avoid juggling the function order by adding a declare statement to the start of your namespace

(declare fun1 fun2 fun3)

(defn fun3 [] (fun1))
(defn fun1 [] (fun2))
(defn fun2 [] 42)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文