Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Functional Style==== The above algorithm can be written even more consistently, using {{code|Stream.iterate}}. The iterate method receives a seed parameter, and a function that specifies what to do for each iteration. In this case, the seed can be a record class with the 2 initial values of the algorithm, and its respective transformation in each iteration. In short, the iterate method makes unnecessary the implementation of a Supplier. <syntaxhighlight lang="java" style="font-size:90%"> record Pair(int a, int b) {}; Stream .iterate(new Pair(0, 1), p -> new Pair(p.b, p.a + p.b)) .limit(10) .map(p -> p.a) .forEach(System.out::println); </syntaxhighlight> |Notes for the C# version: * The method is defined as returning instances of the interface {{csharp|IEnumerable<int>}}, which allows client code to repeatedly request the next number of a sequence. * The {{csharp|yield}} keyword converts the method into a generator method. * The {{csharp|yield return}} statement returns the next number of the sequence and creates a continuation so that subsequent invocations of the {{csharp|IEnumerable}} interface's {{csharp|MoveNext}} method will continue execution from the following statement with all local variables intact. * Tuple-assignment avoids the need to create and use a temporary variable when updating the values of the variables {{mono|a}} and {{mono|b}}. |}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)