Tumgik
Text
Why isn't this in STL?
template<typename Range, typename Pred> void erase_if(Range& range, Pred&& predicate) { for (auto pos {cbegin(range)}, last {cend(range)}; pos != last; (pos = range.erase(pos)) : ++pos); }
0 notes
Text
List stable sort
Not necessarily the fastest thing out there:
class StableComparer<T> : IComparer<T> { private readonly Func<T, IComparable> value; private readonly Func<T, IComparable> order; public StableComparer(Func<T, IComparable> valueSelector, Func<T, IComparable> orderSelector) { value = valueSelector; order = orderSelector; } int IComparer<T>.Compare(T x, T y) => value(x).CompareTo(value(y)).Then(result => result != 0 ? result : order(x).CompareTo(order(y))); } ... collection.Sort(new StableComparer<Item>(item => item.Timestamp, item => item.Id));
0 notes
adventureswithdotnet · 10 years
Text
Multiplying TimeSpans
As in time periods:
static TimeSpan Multiply(this TimeSpan span, int multiplier) => TimeSpan.FromTicks(span.Ticks * multiplier);
0 notes
adventureswithdotnet · 10 years
Text
Dictionary's GetValueOrDefault
Why isn't it already available?
static V GetValueOrDefault<K, V>(this Dictionary<K, V> source, K key) { V value; source.TryGetValue(key, out value); return value; }
0 notes
adventureswithdotnet · 10 years
Text
Weighted mean
static double Average<T>(this IEnumerable<T> source, Func<T, double> selector, Func<T, long> weightSelector) => source.Sum(item => selector(item) * weightSelector(item)) / source.Sum(weightSelector);
0 notes
adventureswithdotnet · 10 years
Text
Enums as collection
When you need to iterate them:
static IEnumerable<T> GetEnums<T>() => Enum.GetValues(typeof(T)).Cast<T>();
0 notes
adventureswithdotnet · 11 years
Text
Safe navigation
C# 6 has the ?. operator, but in case earlier versions must be supported:
static U Then<T, U>(this T source, Func<T, U> predicate) => source == null ? default(U) : predicate(source);
0 notes
adventureswithdotnet · 11 years
Text
Solving Sudoku in F#
Came across this Sudoku solver by Peter Norvig and decided to rewrite in F# (+fsharpx) loosely based on the listed C# one by Richard Birkby:
open FSharpx;open FSharpx.Collections;open System.IO module S=Seq module M=Map let ᶺ=Option.bind let ᵒ i=S.exists((=)i) let ᴓ i=S.filter((<>)i) let Ѧ c=S.length c/3|>(fun l->[S.take l c;S.skip l c|>S.take l;S.skip(l*2)c]) let ₓ a=S.lift2 tuple2 a let α=['1'..'9'] let Ͳ=ₓ α α let ɱ p=S.collect p Ͳ|>S.groupBy fst|>M.ofSeq|>M.map(fun _->S.map snd) let ʋ=ɱ(fun s->S.concat[S.map(fun c->ₓ α [c])α;S.map(fun r->ₓ[r]α)α;S.lift2 ₓ (Ѧ α)(Ѧ α)]|>S.filter(ᵒ s)|>S.map(tuple2 s)) let ɷ=ɱ(fun s->M.find s ʋ|>S.collect(ᴓ s>>S.map(tuple2 s)))|>M.map(fun _->S.distinct>>S.toArray) let rec Ɣ i b d=M.find i b|>ᴓ d|>S.fold(đ i)(Some b) and đ i b d= let р b=S.map(S.filter(fun t->ᵒ d (M.find t b)))>>S.fold(fun b n->ᶺ(fun m->match S.toList n with|[]->None|h::[]->Ɣ h m d|_->b)b)(Some b) let ѵ u=match M.find i u with|[]->None|_::[]->S.fold(fun b n->ᶺ(M.find i>>S.head>>đ n b)b)(Some u)(M.find i ɷ)|_->Some u match b with|Some b when ᵒ d (M.find i b)->(M.updateWith(ᴓ d>>S.toList>>Some)i>>ѵ>>ᶺ (fun m -> M.find i ʋ|>р m))b|_->b let rec ŝ=ᶺ(fun m->match(M.toSeq>>S.sortBy(snd>>S.length)>>S.tryFind(snd>>S.length>>(<)1))m with Some(k,v)->S.map(Ɣ k m)v|>S.tryPick ŝ|_->Some m) let ř=S.zip Ͳ>>S.fold(fun b (k,v)->match b with Some m when ᵒ v α->Ɣ k m v|_->b)(S.map(flip tuple2 α)Ͳ|>M.ofSeq|>Some) let cm s p=Ѧ>>S.map p>>String.concat s let ƭ=ᶺ(M.values>>S.concat>>S.map string>>cm"\n\n"(cm"\n"(cm" "(String.concat"")))>>Some)>>Option.getOrElse"" File.ReadAllLines"top95.txt"|>S.map(ř>>ŝ>>ƭ)|>S.iter(printfn"%A")
Code deliberately messy just to play with definitions, as well as F# features and limitations.
0 notes
adventureswithdotnet · 11 years
Text
WebBrowser Navigating event doesn't like async
async void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { // e.Cancel = true; // This is honored await SlowMethodAsync(); e.Cancel = true; // This is not }
Go figure…
0 notes
adventureswithdotnet · 11 years
Text
Pipelining operations
Workaround for function pipelining in C#:
static U Pipe<T, U>(this T value, Func<T, U> predicate) => predicate(value); static void Pipe<T>(this T value, Action<T> predicate) => predicate(value);
0 notes
adventureswithdotnet · 11 years
Text
Combining collections
static IEnumerable<V> Combine<T, U, V>(this IEnumerable<T> first, IEnumerable<U> second, Func<T, U, V> resultSelector) => // first.SelectMany(a => second.Select(b => resultSelector(a, b))); // first.Join(second, _ => true, _ => true, resultSelector); from a in first from b in second select resultSelector(a, b);
For some reason I prefer the commented version.
0 notes
adventureswithdotnet · 11 years
Text
Constructing disposable resources safely
Code analysis can be a pain for unnecessary reasons sometimes, specially CA2000, so trying to work around the case where the constructor can throw:
T SafeBuildDisposableResource<T>() where T : class, IDisposable, new() { T resource = null; try { resource = new T(); return resource; } catch { if (resource != null) { resource.Dispose(); } throw; } }
And a test:
DataTable GetDataTable() { var resource = SafeBuildDisposableResource<DataTable>(); // Add columns... // Add rows... return resource; }
Meh, but VS 2012 is happy now...
0 notes
adventureswithdotnet · 12 years
Text
SynchronizationContext gotcha for Windows Forms
partial class MainForm : Form { private Progress<ViewProgress> progress = new Progress<ViewProgress>(ProgressHandler); ...
Big no no, there will be no SynchronizationContext at the time of construction and thus the handler will run on the thread pool rather than the UI thread. Construct on MainForm() instead. MSDN documentation remarks ftw once again.
0 notes
adventureswithdotnet · 12 years
Text
Singleton
Still inspired by F#, moving Seq.singleton to C#:
static IEnumerable<T> ToSingleton<T>(this T source) { yield return source; }
0 notes
adventureswithdotnet · 12 years
Text
Some F#
Playing with F# and all the functional awesomeness has been a bless, specially when coming from a Haskell background. And even for the simpler things, avoiding an intermediate state proves itself useful yet again. That C#:
var data = ReadData(dataFile); var resultA = calculateA(data); var resultB = calculateB(data); return Tuple.Create(resultA, resultB);
Becomes:
dataFile |> ReadData |> (fun data -> calculateA data, calculateB data)
Regardless of state, all I need is moving from an input to my results.
1 note · View note
adventureswithdotnet · 12 years
Text
Set Windows Forms control font size
Since Font.Size is read-only. Throws when value is less than or equal to zero:
static void SetFontSize(this Control target, float value) => target.Font = new Font(target.Font.Name, value, target.Font.Style, target.Font.Unit);
0 notes
adventureswithdotnet · 12 years
Text
Expected<T> in C#
Based on Andrei Alexandrescu's Expected<T> for C++, the idea is sort of a Nullable<T> which carries over the failure data:
public class Expected<T> { private T ham; private Exception spam; private Expected() { } // nothing else to do public Expected(T value) { ham = value; HasValue = true; } public Expected(Expected<T> copy) { if (HasValue = copy.HasValue) { ham = copy.ham; } else { spam = copy.spam; } } public bool HasValue { get; private set; } public T Value { get { if (!HasValue) { throw spam; } return ham; } } public static Expected<T> FromException(Exception exception) => new Expected<T> { HasValue = false, spam = exception }; public static Expected<T> FromCode(Func<T> predicate) { try { return predicate(); } catch (Exception e) { return FromException(e); } } public static explicit operator T(Expected<T> value) => value.Value; public static implicit operator Expected<T>(T value) => new Expected<T>(value); public T GetValueOrDefault(T defaultValue = default(T)) => HasValue ? ham : defaultValue; public bool HasException<U>() => spam is U; public override string ToString() => HasValue ? ham.ToString() : spam.ToString(); }
And some tests:
Expected<int> ParseInt(string source) { try { return int.Parse(source); } catch (Exception e) { return Expected<int>.FromException(e); } } ... var test1 = ParseInt("123"); var test2 = ParseInt(null); var test3 = ParseInt("abc"); var test4 = Expected<int>.FromCode(() => int.Parse("123")); var test5 = Expected<int>.FromCode(() => int.Parse("abc")); var test6 = new Expected<int>(test2); Debug.Assert(test1.HasValue && test1.Value == 123); Debug.Assert(test2.HasValue == false); Debug.Assert(test2.HasException<ArgumentNullException>()); Debug.Assert(test3.HasException<ArgumentNullException>() == false); Debug.Assert(test1.HasException<ArgumentNullException>() == false); Debug.Assert(test3.HasException<Exception>()); Debug.Assert(test4.HasValue && test4.Value == 123); Debug.Assert(test5.GetValueOrDefault() == default(int)); Debug.Assert(test5.GetValueOrDefault(4) == 4); Debug.Assert(test6.HasException<ArgumentNullException>());
In my opinion, a lot nicer than TryParse()!
0 notes