Empty sequence when looping on a sequence for the second time - sequence

In stanza, I would like to loop two times over a sequence.
I have something like that:
public defn function1-and-function2 (s:Seqable<Double>) -> [Double, Double]:
[function1(s), function2(s)]
with
public defn function1 (s:Seqable<Double>) -> Double
and
public defn function2 (s:Seqable<Shape>) -> Double
In both function1 and function2, I am looping on the sequence. But when reaching function2, the sequence is empty.

A Seqable is a lazily calculated sequence of values, and in general, you are only allowed to iterate through it once.
Thus, the general solution is to first store all of the values (e.g. in a tuple) and then you can pass this tuple to each of your functions:
val t = to-tuple(s)
[function1(t), function2(t)]
However, for your particular case, it is obvious that function1 and function2 can be calculated independently of each other. So it is possible to iterate through the sequence once, and then concurrently calculate the result of both function1 and function2. There is a fancy function in core called fork-on-seq that lets you do this:
fork-on-seq(s, function1, function2)

Related

Is there a Kotlin std lib function to copy a list, removing all elements equal to ONE single element? A function taking only one non-collection arg?

Given a list of arbitrary objects
input = listOf(a, b, c, a)
... is there a function (with one non-collection argument) in the Kotlin standard library that I can use to make a copy of this list, removing all instances of ONE object?
Something like:
val filtered = input.removeAllInstancesOf(a)
To clarify, I'm aware of other (potential) solutions to this task:
Using the filter function to do this. → val output = input.filterNot { it == a }
Using the minus function with a collection → val output = input.minus(listOf(a))
Using the minus function with a non-collection argument → val output = input.minus(a) ← Only removes the first instance of a!
Removing all instances from a mutable list.
Writing such a function. → Wrap any of the above.
... but I'm wondering why I can't find a function which takes just ONE, non-collection value.
but I'm wondering why I can't find a function which takes just ONE, non-collection value.
Because that's a hyper-specific use-case of the already existing filter function. As you yourself showed it can be done in one line, and is probably the first thing a Kotlin dev would try to do (at least I would). So adding new function to the standard library probably doesn't add much value.

Could someone, please, explain me the implementation of the following "Kotlin Literal high order function"?

I am a newbie in Kotlin, I just started to learn it,
I get the following code example about literal/high order function:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
println ( myHigherOrderFun { "The Number is $it" })
prints "The Number is 5"
Which I have difficulty to understand: the function myHigherOrderFun get a lambda function as parameter but i can't understand, where is the (Int) input parameter? I see is passed in functionArg(5)... but i can't realize how is possible that?
Thanks in advance.
To start from the beginning, in Kotlin functions are first-class types, just like numbers and Strings and stuff.  So a function can take another function as a parameter, and/or return a function as its result.  A function which does this is called a ‘higher-order function’.
And that's what you have in your example!  The line:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
defines myHigherOrderFun() as a function which takes one parameter, which is itself a function taking a single Int parameter and returning a String.  (myHigherOrderFun() doesn't specify an explicit return type, so it's inferred to be a String too.)
The next line is probably where things are less clear:
println(myHigherOrderFun{ "The Number is $it" })
The first non-obvious thing is that it's calling myHigherOrderFun() with a parameter.  Because that parameter is a lambda, Kotlin lets you omit the usual (…), and use only the braces.
The other non-obvious thing is the lambda itself: { "The Number is $it" }. This is a literal function taking one parameter (of unspecified type).
Normally, you'd have to specify any parameters explicitly, e.g.: { a: Char, b: Int -> /* … */ }.  But if there's exactly one parameter, and you aren't specifying its type, then you can skip that and just refer to the parameter as it.  That's what's happening here.
(If the lambda didn't reference it, then it would be a function taking no parameters at all.)
And because the lambda is being passed to something expecting a function taking an Int parameter, Kotlin knows that it must be an Int, which is why we can get away without specifying that.
So, Kotlin passes that lambda to the myHigherOrderFun(), which executes the lambda, passing 5 as it.  That interpolates it into a string, which it returns as the argument to println().
Many lambdas take a single parameter, so it gets used quite a lot in Kotlin; it's more concise (and usually more readable) than the alternative.  See the docs for more info.

Purpose of repeat function

Using kotlin I can repeat an action in at least two ways:
val times = 5
// First option
for (i in 0 until times) {
print("Action $i")
}
// Second option
repeat(times) {
print("Action $it")
}
I'd like to know the purpose of repeat.
Should the traditional for loop be replaced with repeat function if possible?
Or are there special cases for this function?
Are there any advantages in repeat function?
EDIT
I've made some research about this question. As long as kotlin is open source project, I could download the sources and check git history.
I found that
1) repeat function is a replace for times function extension.
public inline fun Int.times(body : () -> Unit)
2) KT-7074. times function has become deprecated. But why?
It's just a matter of convenience (shortens the code). There are even more ways for example using an IntRange and forEach
(0..4).forEach {
println(it)
}
0 1 2 3 4
They all serve the same purpose, so the choice is yours.
You don't need to worry about performance either, since repeat and forEach are inline functions, which means the lambda code is copied over to the call site at compile time.
Next lines are all just my opinion:
there are no special cases when you should or shouldn't use repeat
function.
it has more concise syntax.
In places where you don't need to manipulate the loop counter or need to repeat only some simple action I would use that function.
It's all up to you to decide when and how to use it.
From Standard.kt:
/**
* Executes the given function [action] specified number of [times].
*
* A zero-based index of current iteration is passed as a parameter to [action].
*
* #sample samples.misc.ControlFlow.repeat
*/
#kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
contract { callsInPlace(action) }
for (index in 0 until times) {
action(index)
}
}
As you can see repeat(times) is actually for (index in 0 until times).
There is also a zero-based loop counter and it is: it.
Should the traditional for loop be replaced with repeat function if
possible?
I can't find any reason for that
Or are there special cases for this function?
None I can think of.
Are there any advantages in repeat function?
None I can think of, or maybe(?) just 1:
for educational purposes, I suppose it's easier to teach
that repeat(n) { } performs n iterations of the block of statements inside the curly brackets.

How can I QuickCheck value wrapped by effect in PureScript?

I have a shuffle function for Array:
shuffle:: forall e. Array -> Eff (random :: RANDOM | e) Array
It shuffles an array in a Control.Monad.Eff.Random monad and returns the wrapped one. I want to test the array is shuffled, like to compare the result is different, so I write QuickCheck code like:
quickCheck \arr -> isShuffled (shuffle arr)
However, I'm not sure how to write isShuffled to match type definitions. Since:
There is no unwrapping function like fromJust in Maybe, so it must accept Random Array and return Random Boolean, while I put the checking code in the Monadic expression.
Therefore, the result of isShuffled will not be plain Boolean, but like m Boolean
There is no suitable Testable in purescript-quickcheck for m Boolean, so I may need to create one instance for it, while the comment in QuickCheck refers:
A testable property is a function of zero or more Arbitrary arguments, returning a Boolean or Result. (code)
However, again, I cannot extract/unwrap a value from Random monad, I don't know how to access the boolean inside it and to implement like testableRandomArray to have Boolean or Result from a Random Boolean, unless I use some unsafe features.
I think I should "embed" the line of quickCheck inside a Random monad so I can access the pure Array it shuffled. However, since it is quickCheck to generate the test fixtures, I feel this is weird and no way to do that.

Erlang Looping through a list (or set) to process files

I want to create 16 directories in Erlang.
for ( create_dir("work/p" ++ A, where A is an element in a list [0, 1, ... f]) (sixteen number in hex notation).
I could of course write sixteen lines like: mkdir ("work/p0"), mkdir("work/p1") etc.
I have looked at lists:foreach. In the examples fun is used, is possible to define a function outside the loop and call it?
I am new to Erlang and used to C++ etc.
Yes, it's possible to define a (named) function outside the call to lists:foreach/2. Why would you, though? This is a case when an anonymous function is incredibly handy:
lists:foreach(fun(N) ->
file:make_dir(
filename:join("work", "p"++integer_to_list(N, 16)))
end, lists:seq(0, 15)).
The filename:join/2 call will use the appropriate directory separator to construct the string work/pN, where N is an integer in hex representation constructed using integer_to_list/2, which converts an integer to a string (list) in a given base (16).
lists:seq/2 is a friendly little function that returns the list [A,A+1,A+2,...,B-1,B] given A and B.
Note that you could just as well have used the list comprehension syntax here, but since we're applying functions to a list for the side-effects alone, I chose to stick with a foreach.
If you really want to define a separate function -- let's call it foo and assume it takes 42 arguments -- you can refer to it as fun foo/42 in your code. This expression evaluates to a function object that, like an anonymous function defined inline, can be passed to lists:foreach/2.