Is there any way to not return something using CoffeeScript? - coffeescript

It seems like CoffeeScript automatically returns the last item in a scope. Can I avoid this functionality?

You have to explicitly return nothing, or to leave an expression evaluating to undefined at the bottom of your function:
fun = ->
doSomething()
return
Or:
fun = ->
doSomething()
undefined
This is what the doc recommends, when using comprehensions:
Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.
You could, however, write a wrapper like this:
voidFun = (fun) ->
->
fun(arguments...)
return
(Notice the splat operator here (...))
And use it like this when defining functions:
fun = voidFun ->
doSomething()
doSomethingElse()
Or like this:
fun = voidFun(->
doSomething()
doSomethingElse()
)

Yes , with a return as the last line of a function.
For example,
answer = () ->
42
extrovert = (question) ->
answer()
introvert = (question) ->
x = answer()
# contemplate about the answer x
return
If you'd like to see what js the coffee compiles to, look at this. (I've used coffeescript redux for my example)

Just something fun(ctional)
suppressed = _.compose Function.prototype, -> 'do your stuff'
Function.prototype itself is a function that always return nothing. You can use compose to pipe your return value into this blackhole and the composed function will never return anything.

longRunningFunctionWithNullReturn = ->
longRunningFunction()
null

It seems functions in CoffeeScript must always return something, even null. In C, you have void as a return type.
->, the empty function, compiles to (function() {}), so it's the only function that doesn't return anything.

Related

compactMap() closure fails when adding irrelevant NOP declaration?

Playground
XCode Version 13.3 (13E113)
Swift 5.6
First print of compactMap() closure displays this:
["What\'s", "Going", "On?"]
The second print displays this:
[(), (), ()]
Seems like if I declare anything inside the closure, the output of the closure changes.
print( "What's\nGoing\nOn?".split(separator:"\n").enumerated().compactMap
{ idx, lineText in
lineText
})
print( "What's\nGoing\nOn?".split(separator:"\n").enumerated().compactMap
{ idx, lineText in
let _ : String
lineText
})
Is there a way to wrap some of it to hide the other declaration?
Is the closure confused about the type?
Is there any way to unconfuse it (or me)?
Is it a Swift bug?
Issue is root of why other things I'm trying to with this pattern aren't working.
UPDATE
As per #Shadowrun's answer below, I added a return statement in the 3rd example, but that leads to compile time errors. So is that resolvable?
print( "What's\nGoing\nOn?".split(separator:"\n").enumerated().compactMap
{ idx, lineText in
let _ : String
return lineText
})
expression failed to parse:
error: test playground.playground:38:52: error: generic parameter 'ElementOfResult' could not be inferred
print( "What's\nGoing\nOn?".split(separator:"\n").enumerated().compactMap
^
Swift.Sequence:2:28: note: in call to function 'compactMap'
#inlinable public func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]</b>
If you have a one line closure there's an implicit return, so the first one is returning lineText which is of type string. See "Functions With an Implicit Return" at https://docs.swift.org/swift-book/LanguageGuide/Functions.html
The second one doesn't actually return anything, once it is more than one line, there is no implicit return. So the return type is Void which is also spelled as the empty tuple, () and that's what you get there.
You need to say return lineText explicitly if you mean to return something.
This function:
{ idx, lineText in
let _ : String
lineText // This line evaluates the value of lineText and does nothing with the result
}
does not return a value. Any function that doesn't return a value returns a Void value. Void is a type with only one possible value, called (). Mapping to void is a pointless thing to do. Even if your function did a side effect, like printing something, it wouldn't be good style to use map just for side effects.
You can guard against this kind of mistake by being more explicit about the return type in the closure
{ idx, lineText -> String in ... }

Need help understanding how these two statements are equal

Here is a block of code that is equivalent (to my knowledge) to the other.
let f:()->() = brick
where brick is
func brick()->Void{ print("Throw Brick");}
but I can also write it as
let f = {return brick()}
What is this ^ code doing.
The first code I know makes sense to me. This is where I am defining a variable who's type is of the signature ()->() or ()->Void. And then passing the reference of brick function to the variable.
Thanks
Though in both code snippets, f will behave in the same way when you call it, the code snippets are semantically different.
let f:()->() = brick
This assigns the function brick to the let constant f. Note that the type annotation is not required since the compiler knows that brick is a function that takes no parameters and returns Void, so it can infer that f must also be such a function too. Therefore, you can write it as:
let f = brick
Another way to write functions is to use a closure expression. For example, the following closure expression represents a function that calls brick:
{ return brick() }
Since you omitted the in keyword and didn't use any shorthand argument names ($0, $1 etc), the compiler infers that the closure expression takes no arguments. And since brick() returns Void, the closure expression returns Void too - return brick() means "return what brick() returns". The compiler is able to infer the type of the closure expression, so this is valid:
let f = { return brick() }
This assigns a "closure expression that calls simply calls brick() and returns what it returns" to f.
Depending on how you look at it, this is a bit different from let f = brick, where you are directly assigning brick to f. But in the end, in both cases calling f will do the same thing - you will end up calling brick.
The difference is sort of similar to the difference between let x: Double = 1 and let x = cos(0) - x = 1 in both cases, but one of those ways is more direct.
First of all your two versions are not equivalent. This:
func brick()->Void{ print("Throw Brick");}
let f = {return brick()}
is equated by this:
func brick()->Void{ print("Throw Brick");}
func brickCaller() { return brick() }
let f = brickCaller
Whereas, the equivalent of your
let f:()->() = brick
func brick()->Void{ print("Throw Brick");}
would be simply
let f:()->() = { print("Throw Brick") }
with no intermediary call to brick at all.
So, anyway, I'd put it differently from Sweeper's answer. I'd reply that a function can be declared-with-a-name, using func, or be nameless (anonymous), using a mere function body.
So the point is that in each pair of equivalents, one function has a name-and-declaration of its own, with func, and the other function doesn't — its body is simply assigned directly to the variable f.

How do you call an uncurried function with unit in ReScript/ReasonML?

Say that I have an uncurried function like:
let echo(. a) = a;
I can call this funcition fine with most literals like:
echo(. 1)
echo(. "Hello")
but when I am trying to call it with void, I get an error:
echo(. ()) //This function has arity1 but was expected arity0
As a workaround, I can do this:
let myArg = ()
echo(. myArg)
Is there a way to avoid this?
I like this version as well:
echo(. ignore())
that way I don't need the dummy value workaround
Edit: This version is also now part of the docs: https://rescript-lang.org/docs/manual/latest/function#uncurried-function
It looks like you are trying to call an un curried function that takes one parameter with no arguments because that is what () means right. The only reason it works with
echo(. myArg) is in this case the compiler is declaring an un initialized variable called myArg and passing that to echo.
EDIT: you can look at what I mean at re-script playground here
let echo = (. a) => a;
let k =() => echo(. "String")
let myArg = ()
let s =() => echo (. myArg)
generates
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
function echo(a) {
return a;
}
function k(param) {
return echo("String");
}
function s(param) {
return echo(undefined);
}
var myArg;
exports.echo = echo;
exports.k = k;
exports.myArg = myArg;
exports.s = s;
/* No side effect */
Apparently, this is a known issue in rescript. See: https://github.com/rescript-lang/rescript-compiler/issues/3429

How does a function that returns a function work?

I'm reading Apple's book about Swift and stumbled upon this piece of code, which I after many tries couldn't understand. As far as I understand, this function returns a function. The two last lines of code, as well as all the code, though, are totally bewildering. And how we can assign a function to a variable (the seventh line)? Thank you.
I've typed it myself into the Playground but still don't get it.
func makeIncrement () -> ((Int) -> Int){
func addOne (number: Int) -> Int{
return 1 + number
}
return addOne
}
var increment = makeIncrement()
increment(7)
Functions can be considered objects in Swift (or as first class functions - worth researching).
Therefore may be assigned to variables and to object properties.
So in your code makeIncrement simply returns the function addOne as a variable.
var increment = makeIncrement() can just be seen as assigning the returned function from makeIncrement as a variable (or function object) increment.
We can then freely call the increment function as we would call addOneor any other function really.
A function is something with optional input and a return type. If you alt-click on the var increment you will see that increment is of type ((Int) -> Int). This means that you can input an Int and will return an Int. This is then done in the last line by calling this function.
If you know object-oriented programming, you will know that you can always pass objects around, which also have functions. In this way, in your code, it is doing the same but now we are omitting the object.

What is the purpose to make a function which return a function?

I was reading Apple doc about swift .
it has an example in which it made a function which returns a function
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
So here my concern is what are advantages of this practice and when to use it?
and if some one can also help me with concept of "A function can take another function as one of its arguments." than that will be so kind
Thanks in advance
Here's a really common case of this that you use all the time, probably without even realizing it.
Instance methods are really just class methods that return closures.
Take String.hasPrefix for example, which has type (String) -> (String) -> Bool.
So String.hasPrefix takes String argument, which is the instance the instance method will act upon, and returns a closure of type (String) -> Bool.
We would usually get this closure by using a form like "The quick brown fox".hasPrefix, but we can also use String.hasPrefix("The quick brown fox"), which is equivalent.
The result of these expressions is the hasPrefix function, bound to the specific instance (the String "The quick brown fox") that it will act upon.
We can then invoke this closure with another String argument, which tells it what prefix to look for.
Here's what you might typically write:
let result = "The quick brown fox".hasPrefix("The") // => True
Let's break that down into steps (with type annotations added for emphasis on the types at play):
import Foundation
let instance: String = "The quick brown fox"
let desiredPrefx: String = "The"
let staticMethod: (String) -> (String) -> Bool = String.hasPrefix
let boundInstanceMethod: (String) -> Bool = staticMethod(instance)
let result: Bool = boundInstanceMethod(desiredPrefx) // => true
equivalent:
import Foundation
let instance: String = "The quick brown fox"
let desiredPrefx: String = "The"
let boundInstanceMethod: (String) -> (String) -> Bool = instance.hasPrefix
let result: Bool = boundInstanceMethod(desiredPrefx) // => true
The benefit of creating a function that returns a function is that the inner function remembers the environment that it was created in. Typically, when you call a function, the variables within that function end when the function finishes. By returning a function, however, you create what is called a closure, and this allows you to hold on to the environment that the closure was created in, so you can use it over and over again.
There are many benefits to being able to accept a function as a parameter to another function. For example, you could create a filter function that accepts an array as its first argument and another function as its second. Then, you could call your filter function and pass it a function that would check each element of the array to see if it was even, and return a new array that only contains even values. You could also call the same filter function with a function that checks each element of an array to see if it is odd, and return a new array containing only odd numbers. This makes the filter function far more flexible than it would otherwise be, and allows you to get away with writing less code. Instead of writing a new, complex function every time you want to filter the elements of an array, and having to maintain a potential multitude of filter functions, you only have to write one.
I hope this helps.
makeIncrementer() have a function addOne(number: Int)
That is only eccessable with in makeIncrementer()
Out side of makeIncrementer() we can not access addOne(number: Int).