Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's ambiguous the other way:

   (defn some-string []
      "is this a docstring or a return value?")


Clojure works with it in either case, and it is not ambiguous due to the arity of defn.


I think you're misunderstanding, because (a) no it doesn't, and (b) no it isn't :)

Clojure docstrings need to precede the argument list. e.g. this is correct:

    (defn foo
      "Some docstring"
      []
      "Some return value"))
But this is not:

    (defn foo
      []
      "Some docstring"
      "Some return value"))
It will still compile, but the first string will be treated as an expression, and therefore ignored as it has no side effects.

The reason docstrings in Clojure come before the arguments, is that because if they came after, their effect would be ambiguous, regardless of arity. e.g.

    (defn foo [] "foo")
Is the string supposed to be the return value of the function, or its docstring?


Other Lisps do it that way without a problem:

- If the function body starts with a string literal, it is always the doc-string

- If that string is the only thing in the function body, it is also the return value.


Sure, you can conceive of more complex rules to solve the problem, but that's complicating the syntax for little benefit. You can no longer say "The docstring comes before the arguments". You instead have to say something like "The docstring is the first evaluated expression in the function if the expression is a string, unless the function has multiple arities, in which case the docstring precedes the function's arguments and any isolated string expressions in the bodies will be ignored."




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: