Language integrated query in Kotlin? - linq

I'm working on porting to Kotlin one of my on C# projects which uses certain features of linq. As an example lets take the following linq query:
from a in A
from b in B
from c in C
select fun(a,b,c);
In C# this allows to chain functions of any type then collect the results in an easy to read way which is preetty much may requirement.
This is equivalent (more or less) to:
A.SelectMany(a => B, (a, b) => new {a, b}).SelectMany(t => C, (t, c) => fun( t.a, t.b, c));
It is not a problem to achieve functionality of Enumerable.SelectMany in Kotlin but it is still as noisy as the C# equivalent.
Is there any way to achieve something similar in Kotlin without fiddling explicilty with nested tuples but closer to the linq?

Marko Topolnik provided the following as a comment, but it is actually a valid solution:
A.flatMap { a ->
B.flatMap { b ->
C.map { c ->
fun(a, b, c)
}
}
}

Related

Do any functional programming languages have syntax sugar for changing part of an object?

In imperative programming, there is concise syntax sugar for changing part of an object, e.g. assigning to a field:
foo.bar = new_value
Or to an element of an array, or in some languages an array-like list:
a[3] = new_value
In functional programming, the idiom is not to mutate part of an existing object, but to create a new object with most of the same values, but a different value for that field or element.
At the semantic level, this brings about significant improvements in ease of understanding and composing code, albeit not without trade-offs.
I am asking here about the trade-offs at the syntax level. In general, creating a new object with most of the same values, but a different value for one field or element, is a much more heavyweight operation in terms of how it looks in your code.
Is there any functional programming language that provides syntax sugar to make that operation look more concise? Obviously you can write a function to do it, but imperative languages provide syntax sugar to make it more concise than calling a procedure; do any functional languages provide syntax sugar to make it more concise than calling a function? I could swear that I have seen syntax sugar for at least the object.field case, in some functional language, though I forget which one it was.
(Performance is out of scope here. In this context, I am talking only about what the code looks like and does, not how fast it does it.)
Haskell records have this functionality. You can define a record to be:
data Person = Person
{ name :: String
, age :: Int
}
And an instance:
johnSmith :: Person
johnSmith = Person
{ name = "John Smith"
, age = 24
}
And create an alternation:
johnDoe :: Person
johnDoe = johnSmith {name = "John Doe"}
-- Result:
-- johnDoe = Person
-- { name = "John Doe"
-- , age = 24
-- }
This syntax, however, is cumbersome when you have to update deeply nested records. We've got a library lens that solves this problem quite well.
However, Haskell lists do not provide an update syntax because updating on lists will have an O(n) cost - they are singly-linked lists.
If you want efficient update on list-like collections, you can use Arrays in the array package, or Vectors in the vector package. They both have the infix operator (//) for updating:
alteredVector = someVector // [(1, "some value")]
-- similar to `someVector[1] = "some value"`
it is not built-in, but I think infix notation is convenient enough!
One language with that kind of sugar is F#. It allows you to write
let myRecord3 = { myRecord2 with Y = 100; Z = 2 }
Scala also has sugar for updating a Map:
ms + (k -> v)
ms updated (k,v)
In a language such as Haskell, you would need to write this yourself. If you can express the update as a key-value pair, you might define
let structure' =
update structure key value
or
update structure (key, value)
which would let you use infix notation such as
structure `update` (key, value)
structure // (key, value)
As a proof of concept, here is one possible (inefficient) implementation, which also fails if your index is out of range:
module UpdateList (updateList, (//)) where
import Data.List (splitAt)
updateList :: [a] -> (Int,a) -> [a]
updateList xs (i,y) = let ( initial, (_:final) ) = splitAt i xs
in initial ++ (y:final)
infixl 6 // -- Same precedence as +
(//) :: [a] -> (Int,a) -> [a]
(//) = updateList
With this definition, ["a","b","c","d"] // (2,"C") returns ["a","b","C","d"]. And [1,2] // (2,3) throws a runtime exception, but I leave that as an exercise for the reader.
H. Rhen gave an example of Haskell record syntax that I did not know about, so I’ve removed the last part of my answer. See theirs instead.

Concatenate 2 Enumerated type variable sets

enum sup;
sup=['a','b','c'];
enum sup2;
sup2=['d','e','f'];
enum sup3;
sup3=sup++sup2;
I want to get an new enumerated type sup3 with all a,b,c,d,e,f.Is there any way in minizinc we can do this.
The short answer is no, this is currently not supported. The main issue with the concatenation of enumerated types comes from the fact we are not just concatenating two lists of things, but we are combining types. Take your example:
enum sup = {A, B, C};
enum sup2 = {D, E, F};
enum sup3 = sup ++ sup2;
When I now write E somewhere in an expression, I no longer know if it has type sup2 or sup3. As you might imagine, there is no guarantee that E would have the same value (for the solver) in the two enumerated types, so this can be a big problem.
To shine a glimmer of hope, the MiniZinc team has been working on a similar approach to make this possible (but not yet formally announced). Instead of your syntax, one would write:
enum X = {A, B, C};
enum Y = {D, E, F} ++ F(X);
The idea behind this is that F(X) now gives a constructor for the usage of X in Y. This means that if we see just A, we know it's of type X, but if we see F(A), then it's of type Y. Again, this is not yet possible, but will hopefully end up in the language soon.
More of a comment but here is my example of my need. When doing code coverage and FSM transition analysis I am forced to use exclusion to not analyze some transitions for the return_to_state, in the code below. If instead I could use concatenated types as shown, I would have more control over the tools reporting missing transitions.
type Read_states is (ST1);
type Write_states is (ST2, ST3, ST4);
type SPI_states is (SPI_write);
type All_States is Read_states & Write_states & SPI_states;
I could make return_to_state of type Write_states and FRAM_state of type All_states and then not have to put in exclusions in my FSM analysis.

How do I concisely write a || b where a and b are Optional values?

I'm happy with an answer in any language, but I ultimately want an answer in Java. (Java 8+ is fine. Not limited to Java 8. I've tried to fix the tags.)
If I have two Optional<Integer> values, how do I concisely compute the equivalent of a || b, meaning: a, if it's defined; otherwise b, if it's defined; otherwise empty()?
Optional<Integer> a = ...;
Optional<Integer> b = ...;
Optional<Integer> aOrB = a || b; // How to write this in Java 8+?
I know that I can write a.orElse(12), but what if the default "value" is also Optional?
Evidently, in C#, the operator ?? does what I want.
In java-9 you can follow any of these :
✓ Simply chain it using the or as :-
Optional<Integer> a, b, c, d; // initialized
Optional<Integer> opOr = a.or(() -> b).or(() -> c).or(() -> d);
implementation documented as -
If a value is present, returns an Optional describing the value,
otherwise returns an Optional produced by the supplying function.
✓ Alternatively as pointed out by #Holger, use the stream as:-
Optional<Integer> opOr = Stream.of(a, b, c, d).flatMap(Optional::stream).findFirst();
implementation documented as -
If a value is present, returns a sequential Stream containing only
that value, otherwise returns an empty Stream.
Optional<Integer> aOrB = a.isPresent() ? a : b;
In java-8 we don't have any solution to easy chain Optional objects, but you can try with:
Stream.of(a, b)
.filter(op -> op.isPresent())
.map(op -> op.get())
.findFirst();
In java9 you can do:
Optional<Integer> result = a.or(() -> b);
In java-8 if you want something close to the Optional::stream mechanic, you could do
Stream.of(a, b)
.flatMap(x ->
x.map(Stream::of)
.orElse(Stream.empty())
)
.findFirst()
Hi you can do something like this.
a.orElse(b.orElse(null));

How to sort and filter backbone collection

relatively new to backbone. I'm trying to filter and sort a collection before passing off to the template. I can easily sort OR filter, but I can't figure out how to do both. I tried chaining them, creating a variable to hold the filter then sort on that, but can't get anything to work. Any advice?? Thanks!
# Can filter like this:
monday = #collection.where({ target: '#day-mon' })
# Can sort like this:
mondaySorted = #collection.sortBy (t) -> t.get('order')
# Doesn't work:
mondayFilteredSorted = #collection.where({ target: '#day-mon' }).sortBy (t) -> t.get('order')
# Doesn't work:
mondaySorted = monday.sortBy (t) -> t.get('order')
Your problem is that where and sortBy return arrays — not collections — and arrays don't have where or sortBy methods. As soon as you where or sortBy, you lose access to the Backbone collection and Underscore utilities.
You can of course use Underscore directly on the array that where gives you:
_(#collection.where(target: '#day-mon')).sortBy (t) -> t.get('order')
or you could use chain and filter:
#collection.chain().filter((m) -> m.get('target') == '#day-mon').sortBy((m) -> m.get('order')).value()
where is a Backbone collection method so you have to drop down to Underscore's filter if you want to chain.
You could also use the standard Array::sort:
by_order = (a, b) ->
[ a, b ] = [ a.get('order'), b.get('order') ]
return 1 if(a > b)
return -1 if(a < b)
return 0
#collection.where(target: '#day-mon').sort(by_order)
I find this version a little easier on the eyes if you don't use an anonymous function with sort.
Demo: http://jsfiddle.net/ambiguous/N6AT7/1/

missing standard linq query operator?

Is there a linq operator 'x' that does the following:
(1,2,3) 'x' (4,5,6) = ((1,4),(2,5),(3,6))
Geez and I can't remember the standard functional programming name either..
In .NET 4.0, Zip takes two IEnumerable and a function to combine an element from each into a single result. It emits an IEnumerable of the results.
In your example you would use (a, b) => new Tuple<int, int>(a, b) as the combining function.

Resources