Why force function bodies to be single expression? #394
-
Hi all. I just came across this project yesterday and found the concept really intriguing. Really like the type safety and immutable objects in particular. After tinkering in the sandboxes for a while, one thing I found unusual, compared to other languages that I use, was the restriction that function bodies must contain one single expression. I was curious whether someone could explain the reasoning behind this. Is it just something that makes things easier in the compiler? Or is there some deeper conceptual reason for the restriction? Or does it just encourage developers to use a particular 'style' of code? It seems puzzling to me, especially given that in practice I've found that I can pretty much sidestep the restriction by moving multiple steps into a where block, then use the single expression in my function body basically like a return statement. A very simple example below is this function for multiplying 2 complex numbers:
Is a function like that considered bad practice? Am I abusing the language in some way here? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hi, and welcome 👋
It has a number of reasons:
Not at all, that's the reason it's there 🙂 Lately I'm favoring
Also there is an other discussion here that related to this (about to reduce the nesting and indentation) #180 Let me know if you need more information 👍 |
Beta Was this translation helpful? Give feedback.
-
Hi Szikszai, thanks for the reply, very interesting, as is the discussion in #180 Your example does make me wonder though... in this case the inputs are all numbers, we're just doing some arithmetic, there are no errors that could be thrown, so the try{} block doesn't really serve any purpose at all, apart from 'artificially' making a 3 step function into a single expression. Wouldn't it be much easier If we could just do this:
IE treat any function body as being implicitly wrapped in a |
Beta Was this translation helpful? Give feedback.
Hi, and welcome 👋
It has a number of reasons:
Not at all, that's the reason it's there 🙂
Lately I'm favoring
try
blocks towhere
blocks (might deprecate them in the future):