Recent Entries 10
- pattern minor 112d agoTable builder patternTrying to combine functional style (immutable objects) and flexibility of property setters. For the sake of example, let’s say we have a soil types table with two attributes: Color and Name. I am looking for a way to alternate Names, but not Color. Here is how I solved it: ``` // retrieving: all objects are immutable SoilTypes types = SoilTypes.Default; ISoilType clay1 = types.Clay; ISoilType clay2 = types[3]; // derive an alternated immutable copy SoilTypes altTypes = types .With(tt => { // tt.SensitiveFines.Color is still read only tt.SensitiveFines.Name = "Very sensitive fines!"; tt[2].Name = "Purely Organic soil!"; }); // retrieving: everything is immutable ISoilType sensitiveFines = altTypes.SensitiveFines; ``` Where this interface is immutable: ``` public interface ISoilType { Color Color { get; } string Name { get; } } ``` And this class is mutable: ``` public class SoilType : ISoilType { public static implicit operator SoilType((Color Color, string Name) tuple) => new SoilType(tuple.Color, tuple.Name); internal SoilType(ISoilType source) : this(source.Color, source.Name) { } internal SoilType(Color color, string name) { Color = color; Name = name; } public Color Color { get; } public string Name { get; set; } } ``` And this non-generic class is immutable: ``` public class SoilTypes : SoilTypes { public static SoilTypes Default = new SoilTypes( (White, "Undefined"), (Red, "Sensitive Fines"), (Green, "Organic Soil"), (Blue, "Clay"), (Orange, "Silty Clay")); public SoilTypes(params SoilType[] types) : base(types) { } public SoilTypes With(Action> update) { var copy = this .Select(t => new SoilType(t)) .ToArray(); update(new
- pattern minor 112d agoSearching files in directory with various filtersRequirements Note: the requirements are invented by me for practicing functional programming. Functional Requirements Given a directory, all files below the directory (and its sub directories) should be filtered by one of the available filter conditions and then printed to the console. The filter condition can be a) a filter function based on a `FileInfo` object - If the file passes the filter, the full path should be printed to console b) a `Regex` that tries to match the content of the file. - Binary files should be always filtered out - If the file passes the filter, the full path should be printed to the console - For each matching line, the line number and the full line should be printed to the console Technical Requirements - the solution should be as functional as possible - the solution should work without mutable state - For performance reasons, the whole program should work lazy (we don't want to create a large list of all files and it's state and finally working on that data structure) Solution Usage ``` [] let main argv = let path = @"C:\Temp\CommandLineFSharp" // regex file content fiter let regex = Regex("Regex", RegexOptions.Compiled ||| RegexOptions.IgnoreCase) let title = "All files that match the regex 'Regex'" let allFilesContainingError = FileContentRegexFilter(title, regex) findIn path allFilesContainingError // FileInfo filter let title = "All files whose name start with 'A'" let allFilesStartingWithA = FileInfoFilter(title, fun fi -> fi.Name.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)) findIn path allFilesStartingWithA Console.ReadLine() |> ignore 0 ``` Output ``` /*-------------------------------------------------------------------------------- All files that match the regex 'Regex' -------------------------------------------------------------------------------- C:\Temp\CommandLineFSharp\FileSystem.fs [line: 18] | FileContentRegexFilter of St
- pattern minor 112d agoRefactoring an Object Walker utility function in JavascriptI'm refactoring some code, essentially a dot-notation walker for objects. I've abstracted things quite a bit, I'm to the point any more and I begin to loose readability. It all hinges on this one function objectWalker, which does the actual object traversals. I can control what happens by passing in different callbacks to handle key points in the processes. ``` function objectWalker (paths, obj, onEnd, enRoute, onEach) { idx = -1, nextContext = prevContext = obj; const len = paths ? paths.length : 0; const lastStep = len ? len - 1 : 0; while (nextContext != null && ++idx < len) { if (onEach) nextContext = onEach(nextContext, idx, paths, prevContext); if (idx !== lastStep) { prevContext = nextContext; nextContext = (!dotWalker.objectHas(nextContext, paths[idx])) ? enRoute(nextContext, idx, paths, prevContext) : nextContext[paths[idx]]; } else { prevContext = paths.length === 1 ? nextContext : prevContext[paths[idx - 1]]; return onEnd(nextContext, idx, paths, prevContext ); } if(!nextContext) return nextContext; } return nextContext; } ``` Pretty simple, and here are some of the callbacks i can send in. ``` dotWalker.onEnd = function(context, idx, dotPathss, prevContext) { if (idx === 0) { return dotWalker.objectHas(context, dotPathss[idx]) ? context[dotPathss[idx]] : undefined; } else { return prevContext[dotPathss[idx]]; } } dotWalker.onEndAssigner = function(value){ return function(context, idx, dotPathss, prevContext) { return prevContext[dotPathss[idx]] = value, prevContext[dotPathss[idx]]; } } dotWalker.enRouteMapper = function(context, idx, dotPathss, prevContext) { return context[dotPathss[idx]] = {}, context[dotPathss[idx]]; } dotWalker.enRoute = function(context, idx, dotPathss, prevContext) { return dotWalker.objectHas(context, dotPathss[idx]) ? context[dotPathss[idx]] : undefined ; } dotWalker.on
- pattern moderate 112d agoComplex scientific formula for nuclear magnetic resonanceI've been reading "clean code" tutorials, and I definitely see the value of using good names that "document themselves" to make intent clear. However, what can be done about complex formulas where describing the meaning of a symbol is difficult? My solution is to include a reference to the math source, and then use names that relate as closely as possible to the published formula. The code would be unintelligible to another programmer, however, if they didn't have access to the source. For example, I have a Python program that includes this function factory. The returned function is used elsewhere to plot a graph. The code itself looks like a nightmare: ``` def dnmr_twosinglet(va, vb, ka, wa, wb, pa): """ Accept parameters describing a system of two exchanging, uncoupled nuclei, and return a function that requires only frequency as an argurment, that will calculate the intensity of the DNMR lineshape at that frequency. :param va: The frequency of nucleus 'a' at the slow exchange limit. va > vb :param vb: The frequency of nucleus 'b' at the slow exchange limit. vb state b :param wa: The width at half heigh of the signal for nucleus a (at the slow exchange limit). :param wb: The width at half heigh of the signal for nucleus b (at the slow exchange limit). :param pa: The fraction of the population in state a. :param pa: fraction of population in state a wa, wb: peak widths at half height (slow exchange), used to calculate T2s returns: a function that takes v (x coord or numpy linspace) as an argument and returns intensity (y). """ """ Formulas for simulating two uncoupled spin-1/2 nuclei are derived from: Sandstrom, J. "Dynamic NMR Spectroscopy". Academic Press, 1982, p. 15. """ pi = np.pi pi_squared = pi ** 2 T2a = 1 / (pi * wa) T2b = 1 / (pi * wb) pb = 1 - pa tau = pb / ka dv = va - vb Dv = (va + vb) / 2 P = tau * (1 / (T2a * T2b) + pi_squared
- pattern minor 112d agoReduce namespacesI have a collection of full type names where I need to reduce common namespaces. For this purpose I wrote two extensions. The first one explodes each namespace into pieces and the second one removes the first name for as long as all first names are equal thus reducing each namespace. ``` static class Namespace { public static IEnumerable> ExplodeNamespaces(this IEnumerable namespaces) { return namespaces.Select(Split('.')); Func> Split(params char[] separators) => s => s.Split(separators); } public static IEnumerable> ReduceNamespaces(this IEnumerable> namespaces) { while (IsFirstCommon(namespaces)) { namespaces = namespaces.Select(SkipFirst()); } return namespaces; bool IsFirstCommon(IEnumerable> values) => values.Select(ns => ns.FirstOrDefault()).Distinct().Count() == 1; Func, IEnumerable> SkipFirst() => values => values.Skip(1); } } ``` Example: ``` var namespaces = new[] { "foo.waldo.bar.baz.qux", "foo.waldo.bar.baz.quux", "foo.waldo.bar.baaz.qux", "foo.waldo.baar", }; namespaces.ExplodeNamespaces().ReduceNamespaces().Dump(); ``` Result: `bar baz qux bar baz quux bar baaz qux baar `
- pattern minor 112d agoFunctional Html builderThis is my third attempt to create a easy to use html builder because I wasn't really satisfied with the first one that wasn't extendable at all and even the one using dynamics wasn't much better. It was difficult to use due to everything being dynamic and had to be casted everywhere but what's worse it was hard to find the bug if something went wrong. This time I tried to do it the functional way. You validate how well I did or not. Based on your suggestions I now use an interface for the base definition: ``` public interface IMarkupElement : ICollection { string Name { get; } IDictionary Attributes { get; } IMarkupElement Parent { get; set; } int Depth { get; } } ``` and derive two types from it. The actual markup-element ``` [DebuggerDisplay("{DebuggerDisplay,nq}")] public class MarkupElement : IMarkupElement { private readonly List _content = new List(); public MarkupElement(string name, IEnumerable content) { Name = name.NonEmptyOrNull() ?? throw new ArgumentNullException(nameof(name)); Add(content ?? throw new ArgumentNullException(nameof(content))); Attributes = new Dictionary(StringComparer.OrdinalIgnoreCase); } private string DebuggerDisplay => $""; #region IMarkupElement public static IMarkupElement Builder => new NullMarkupElement(); public string Name { get; } public IDictionary Attributes { get; } public IMarkupElement Parent { get; set; } public int Depth { get { var parent = Parent; var depth = parent != null ? 1 : 0; while ((parent = parent?.Parent) != null) depth++; return depth; } } #endregion #region ICollection public int Count => _content.Count; public bool IsReadOnly => false; public void Add(object item) { if (item == null) return; switch (item) { case IMarkupElement e: e.Parent = this; break; case
- pattern minor 112d agoFunctional Pascal triangle in Python (working version)This is actually a follow-up question of Yet another Pascal triangle in Python written in functional programming pattern, which is put on hold for posting broken code. Again, this is my implementation of a Pascal program, which is used to print an n-order Pascal triangle. I write it to familiarize myself with Python's Functional Programming Modules. Some changes have been made to get the code work and make it more "functional" ``` #!/usr/bin/env python3 import operator from itertools import starmap, tee def pairwise(iterable): """ s -> (s0,s1), (s1,s2), (s2,s3), ... https://docs.python.org/3/library/itertools.html#itertools-recipes """ a, b = tee(iterable) next(b, None) return zip(a, b) def pascal_row(n): """ Return a generator that yields the nth row of a Pascal triangle """ if n 0: print_pascal(n-1) print(list(pascal_row(n))) print_pascal(10) ``` Output: ``` [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] ``` Please let me know if this piece of code isn't reflecting the essence of functional programming correctly.
- pattern minor 112d agoRefactoring away from exceptionsWhat do you use for refactoring away from exceptions while programming functional in C#? I defined this class to hold function outcome: ``` public class Result { public static readonly Result OK = new Result(); public static implicit operator Result(Exception error) => new Result(error); protected Result(Exception error = null) { Error = error; } public Exception Error { get; } public bool Succeeded => Error == null; public bool Failed => !Succeeded; public override string ToString() => Succeeded ? "OK" : Error.Message; } ``` And its subclass to hold return value where necessary: ``` public class Result : Result, IEnumerable { public static implicit operator Result(Exception error) => new Result(error); public static implicit operator Result(T value) => new Result(value); public static implicit operator T(Result result) { if (result.Failed) throw result.Error; return result.Value; } protected Result(T value) : base(error: null) { Value = value; } protected Result(Exception error) : base(error) { } T Value { get; } IEnumerable Values => Failed ? new T[0] : new[] { Value }; public IEnumerator GetEnumerator() => Values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } ``` It is enumerable, exposing 0..1 elements, so amount of if-statements can be reduced. Usage: ``` var r1 = Div( Div(100, 10), Div(10, 2)); var r2 = Div( Div(100, 10), Div(0, 0)); Console.WriteLine(r1.Succeeded); // True Console.WriteLine(r1.Count()); // 1 Console.WriteLine(r1); // 2 Console.WriteLine(r2.Succeeded); // False Console.WriteLine(r2.Count()); // 0 // Console.WriteLine(r2); // throws DivideByZeroException ``` Where: ``` static Result Div(Result a, Result
- pattern minor 112d agoFunctional way to have two toggles that turn each other offI have two sets of toggles that need to "uncheck" each other. This is my current solution which is working. Can it somehow get more functional/elegant? ``` let unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar]; let availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar]; flipToggles(firstToggles, secondToggles) flipToggles(secondToggles, firstToggles) function flipToggles(firstToggles, secondToggles) { firstToggles.forEach(function (toggle) { on(toggle, "change", function () { secondToggles.forEach(function(element) { element.checked = false }) }) }) } ```
- pattern minor 112d agoCoin Change Kata in ImmutableJSI'm preparing for a job as a junior/intermediate JS developer. I'm comfortable with my ability to think in higher-order functions, but less confident in my syntax and style (I have more experience in Clojure, ClojureScript). This is simple but I welcome your comments. ``` import { Map } from 'immutable'; const coinChanger = (d, m) => { // d for denominations, m for money const denoms = d.sort((a,b) => b-a) const coinCounter = (coin, amount) => { const coins = Math.floor(amount / coin); const remainder = amount % coin; return Map({}).set(coin, coins).set("remainder", remainder); }; const coinMap = denoms.reduce((result, coin) => { const amount = result.get("remainder"); const coinCount = coinCounter(coin, amount); return result.merge(coinCount); }, Map({"remainder": m})); return coinMap; }; console.log(coinChanger([1, 5], 11)); console.log(coinChanger( [25, 10, 5, 1], 192 )); console.log(coinChanger([25, 2], 105)); ```