Last active
November 26, 2017 23:45
-
-
Save battmanz/8c0391d38333384386b66621c6b158f2 to your computer and use it in GitHub Desktop.
Demonstrates using the Enumerable.Select method with a partially applied function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| using System.Web.Script.Serialization; | |
| class Main { | |
| public static void Main (string[] args) { | |
| string username = "George"; | |
| string[] orderedHeroes = { "Luke Skywalker", "Han Solo", "Leia Organa", "Rey", "Finn", "Poe Dameron" }; | |
| // Store CreateRanking in a variable as a first-class function. | |
| Func<string, string, int, Ranking> createRanking = CreateRanking; | |
| var partialCreateRanking = ApplyPartial(createRanking, username); | |
| Output(orderedHeroes.Select(partialCreateRanking)); | |
| // Output: [ | |
| // {'username':'George','rebel':'Luke Skywalker','index':0}, | |
| // {'username':'George','rebel':'Han Solo','index':1}, | |
| // {'username':'George','rebel':'Leia Organa','index':2}, | |
| // {'username':'George','rebel':'Rey','index':3}, | |
| // {'username':'George','rebel':'Finn','index':4}, | |
| // {'username':'George','rebel':'Poe Dameron','index':5} | |
| // ] | |
| } | |
| // This is Jon Skeet's implementation of partial application. | |
| static Func<T2, T3, TResult> ApplyPartial<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> function, T1 arg1) { | |
| return (b, c) => function(arg1, b, c); | |
| } | |
| // Since C# doesn't have object literals, we need a class to represent a ranking. | |
| static Ranking CreateRanking(string username, string hero, int index) { | |
| return new Ranking(username, hero, index); | |
| } | |
| static void Output(IEnumerable<Ranking> rankings) { | |
| var json = new JavaScriptSerializer().Serialize(rankings.ToArray()); | |
| Console.WriteLine(json); | |
| } | |
| } | |
| public class Ranking { | |
| public Ranking(string username, string hero, int index) { | |
| Username = username; | |
| Hero = hero; | |
| Index = index; | |
| } | |
| public string Username { get; private set; } | |
| public string Hero { get; private set; } | |
| public int Index { get; private set; } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment