Skip to content

Instantly share code, notes, and snippets.

@AlexeyRaga
Last active August 29, 2015 14:02
Show Gist options
  • Save AlexeyRaga/02975952b9b21ca56b5e to your computer and use it in GitHub Desktop.
Save AlexeyRaga/02975952b9b21ca56b5e to your computer and use it in GitHub Desktop.
C# without async/await
public static void MappingExample()
{
var averages = Html
.Download("http://github.com")
.Select(html => {
var links = Html.ParseLinks(html);
var averageLength = links.Average(x => x.Length);
return String.Format("{0} links found, average length is {1}", links.Count, averageLength);
});
Console.WriteLine(averages.Result);
}
public static void CompositionExample()
{
var linkAndTitle = from g in Html.Download("http://github.com")
let l = Html.ParseLinks(g).First()
from e in Html.Download(l)
select Tuple.Create(l, Html.ParseTitle(e));
Console.WriteLine(linkAndTitle.Result);
}
public static class Html
{
public static Task<String> Download(string url)
{
var cli = new System.Net.WebClient();
return Task.Factory.StartNew(() => cli.DownloadString(url));
}
public static IList<String> ParseLinks(string content) { return "href=[\"\'](http://[^\"\']+)".r().All(content); }
public static string ParseTitle(string html) { return @"<title>(.+)</title>".r().First(html); }
}
public static class Async
{
//Making Task a [Endo]Functor (kind of); An incarnation of FMap
public static Task<B> Select<A, B>(this Task<A> task, Func<A, B> selector)
{
return task.ContinueWith(ta => selector(ta.Result));
}
//Making Task a Monad (kind of); an incarnation of Bind
public static Task<C> SelectMany<A, B, C>(this Task<A> task, Func<A, Task<B>> bind, Func<A, B, C> selector)
{
return task.Select(ta => bind(ta).Select(tb => selector(ta, tb))).Unwrap();
}
public static Task<A> Lift<A>(Func<A> func) { return Task.Factory.StartNew(func); }
}
public static class StringExtensions
{
public static Regex r(this string pattern) { return new Regex(pattern); }
public static string First(this Regex pattern, string content) { return pattern.Match(content).Groups[1].Value; }
public static string FirstMatch(this string pattern, string content) { return pattern.r().First(content); }
public static IList<string> All(this Regex pattern, string content) {
return pattern.Matches(content)
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment