Is it good practice to use run function instead of return in Kotlin? - return

Kotlin has an extension function run.
/**
* Calls the specified function [block] and returns its result.
*/
#kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R = block()
And run function can be used instead of return.
// an example multi-line method using return
fun plus(a: Int, b: Int): Int {
val sum = a + b
return sum
}
// uses run instead of return
fun plus(a: Int, b: Int): Int = run {
val sum = a + b
sum
}
Which style is better?

For more complicated functions the first option will be more readable.
For simple functions I would suggest taking a look at Single-expression function syntax.
fun plus(a: Int, b: Int): Int = a + b

Related

MutableStateFlow for methods

I’m trying to make my methods reactive to update the view in Compose. How to do it properly?
interface Foo{
val a: Int
fun bar(): Int
fun foo(): MutableStateFlow<Int> = MutableStateFlow(bar() * a)
}
//#Composable
val foo by fooImpl.foo().collectAsState()
P.S. Currently I made a hack: empty usage a variable a participated in calculations. But it’s not good.
val a = fooImpl.collectAsState()
a
One way to do it - subscribe to all variables used in a method.
var a = MutableStateFlow(0)
fun bar() = a.value +1
fun chad() = 42
fun foo() = bar() * chad()
val foo: Flow
get() = a.map { (it + 1) * chad() }
fun useFoo() = runBlocking {
withContext {
foo.collect {
something(it)
}
}
}

Uncurrying curried Function in Swift

I have a function, which takes two arguments and returns a single value.
For example
func sum(x: Int, y: Int) -> Int {
return x + y
}
Next step is to use a currying to get a function which takes the only first argument and return a closure with an appropriate signature.
Also, I wrote a type alias to bring more clearness of the result type.
typealias EscapingClosure<A, B> = (A) -> B
func curry<A, B, C>(_ f: #escaping (A, B) -> C) -> EscapingClosure<A, (B) -> C> {
return { (a: A) -> ((_ b: B) -> C) in
return { (b: B) -> C in f(a, b) }
}
}
But then I remembered about uncurry function which should return a default sum function signature if I'll apply it on the curryied result.
So I tried to implement a variation of uncurry, and what I'll get at the result:
func uncarry<A, B, C>(_ f: #escaping EscapingClosure<A, (B) -> C>) -> (A, B) -> C {
return { (a: A, b: B) -> C in
return f(a)(b)
}
}
But here's a problem - I can't use this uncurry function with the result of currying on sum function, because uncurry requires only #escaping parameter where curryied function returns a non-escaping variation.
Here's a Swift compiler error:
Cannot convert value of type '((A) -> Void) -> ()' to expected argument type '(_) -> (_) -> _'
Does anyone know are there any ways to create uncurry function in Swift which would be applicable to the curryied function result.
Your uncurry function can do just that, uncurry curried functions:
let currableSum = curry(sum)
let uncurriedSum = uncurry(currableSum)
let add100 = currableSum(100)
print(add100(23)) // => 123
print(uncurriedSum(2, 2)) // => 4
The issue is that you're mistaking uncurrying for unapplying. Once you've partially or fully applied a curried function (or any function, for that matter), there's no mechanism to go back, to get the original function that produced the result.
uncurry(add100) // ❌ can't "unapply" a partially applied function
Imagine if that were the case. Every integer, string, and other value would have to remember a history of what functions caused it. I can't think of a single use case for that. For one, it would require dynamic typing (or forced compile-time casting in a static language like Swift), because you can't predict the signature of an arbitrary function that produces a given result.
As #Alexander write above, I can easily use uncurry function for curried result of the sum().
I just made an error when passed a result value of the curried function.

F# Curried add20 function

If anyone can point me in the direction of why this works it would be greatly appreciated.
It was from my first f# lab in class.
How is add20 working when I have no parameters set to it(Problem 2C2).
////function that adds 10 to it
////Problem 2C1 ///
let k = 10
let add10 z k = z + k
////End Problem 2C1///
////Problem 2C2 ///
let z = 20
let add20 = add10 z
////End Problem 2C2//
If you define an add function that looks like this (note that your add10 function is actually adding its two parameters, not the k constant defined on the previous line):
let add a b = a + b
The F# compiler will report that the function has a type int -> int -> int. Now, you can actually read this in two ways:
int -> int -> int is a function that takes one int another int and produces int
int -> (int -> int) is a function that takes int and returns int -> int.
That is, you call it with one number. It returns a function that takes the other number and returns the total sum.
So, when you write add 32 10, you are using it in the way (1). When you write add 10, you get back a function as described in (2).

How to do 'function pointers' in Rascal?

Does Rascal support function pointers or something like this to do this like Java Interfaces?
Essentially I want to extract specific (changing) logic from a common logic block as separate functions. The to be used function is passed to the common block, which then call this function. In C we can do this with function pointers or with Interfaces in Java.
First I want to know how this general concept is called in the language design world.
I checked the Rascal Function Helppage, but this provide no clarification on this aspect.
So e.g. I have:
int getValue(str input) {
.... }
int getValue2(str input){
... }
Now I want to say:
WhatDatatype? func = getValue2; // how to do this?
Now I can pass this to an another function and then:
int val = invoke_function(func,"Hello"); // how to invoke?, and pass parameters and get ret value
Tx,
Jos
This page in the tutor has an example of using higher-order functions, which are the Rascal feature closest to function pointers:
http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Concepts/Functions/Functions.html
You can define anonymous (unnamed) functions, called closures in Java; assign them to variables; pass them as arguments to functions (higher-order functions); etc. Here is an example:
rascal>myfun = int(int x) { return x + 1; };
int (int): int (int);
rascal>myfun;
int (int): int (int);
rascal>myfun(3);
int: 4
rascal>int applyIntFun(int(int) f, int x) { return f(x); }
int (int (int), int): int applyIntFun(int (int), int);
rascal>applyIntFun(myfun,10);
int: 11
The first command defines an increment function, int(int x) { return x + 1; }, and assigns this to variable myfun. The rest of the code would work the same if instead this was
int myfun(int x) { return x + 1; }
The second command just shows the type, which is a function that takes and returns int. The third command calls the function with value 3, returning 4. The fourth command then shows a function which takes a function as a parameter. This function parameter, f, will then be called with argument x. The final command just shows an example of using it.

Return a closure from a function

Note that this question pertains to a version of Rust before 1.0 was released
Do I understand correctly that it is now impossible to return a closure from a function, unless it was provided to the function in its arguments? It is very useful approach, for example, when I need the same block of code, parameterized differently, in different parts of program. Currently the compiler does not allow something like this, naturally:
fn make_adder(i: int) -> |int| -> int {
|j| i + j
}
The closure is allocated on the stack and is freed upon returning from a function, so it is impossible to return it.
Will it be possible to make this work in future? I heard that dynamically-sized types would allow this.
This can't ever work for a stack closure; it needs to either have no environment or own its environment. The DST proposals do include the possibility of reintroducing a closure type with an owned environment (~Fn), which would satisfy your need, but it is not clear yet whether that will happen or not.
In practice, there are other ways of doing this. For example, you might do this:
pub struct Adder {
n: int,
}
impl Add<int, int> for Adder {
#[inline]
fn add(&self, rhs: &int) -> int {
self.n + *rhs
}
}
fn make_adder(i: int) -> Adder {
Adder {
n: int,
}
}
Then, instead of make_adder(3)(4) == 7, it would be make_adder(3) + 4 == 7, or make_adder(3).add(&4) == 7. (That it is Add<int, int> that it is implementing rather than just an impl Adder { fn add(&self, other: int) -> int { self.n + other } is merely to allow you the convenience of the + operator.)
This is a fairly silly example, as the Adder might just as well be an int in all probability, but it has its possibilities.
Let us say that you want to return a counter; you might wish to have it as a function which returns (0, func), the latter element being a function which will return (1, func), &c. But this can be better modelled with an iterator:
use std::num::{Zero, One};
struct Counter<T> {
value: T,
}
impl<T: Add<T, T> + Zero + One + Clone> Counter<T> {
fn new() -> Counter<T> {
Counter { value: Zero::zero() }
}
}
impl<T: Add<T, T> + Zero + One + Clone> Iterator<T> for Counter<T> {
#[inline]
fn next(&mut self) -> Option<T> {
let mut value = self.value.clone();
self.value += One::one();
Some(value)
}
// Optional, just for a modicum of efficiency in some places
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(uint::max_value, None)
}
}
Again, you see the notion of having an object upon which you call a method to mutate its state and return the desired value, rather than creating a new callable. And that's how it is: for the moment, where you might like to be able to call object(), you need to call object.method(). I'm sure you can live with that minor inconvenience that exists just at present.

Resources