Author Archives: Adam Z

Elm on input event

Update 05/16/2016: And the stuff below becomes completely irrelevant with Elm 0.17. Just use the new Events.onInput.

This could be tricky at first, since Elm doesn’t provide (yet) a built-in onInput handler. Rather, you have to use something a little more generic like this:
on “input” targetValue (\v -> Signal.message address v)

This will send user input to the designated address. Or, say if you want to send it to some action, then you could write something like this:

on "input" targetValue (\v -> Signal.message address (action v))

To deconstruct what’s going on here, let’s look at all of the arguments:
“input” – the type of event
targetValue – A Json.Decoder for grabbing ‘’ from the triggered event.
(\v -> Signal.message address (action v)) – function that handles the input value

And if you look at the definition of onClick, it basically is a shortcut for on “click”:

messageOn : String -> Signal.Address a -> a -> Attribute
messageOn name addr msg =
on name value (\_ -> Signal.message addr msg)

onClick : Signal.Address a -> a -> Attribute
onClick =
messageOn “click”

ESLint with Visual Studio 2015

If you used Web Essentials as your linter, you probably learned by now that it doesn’t provide that functionality anymore in VS 2015.
One way to fix it is to start using tools like gulp… or you could install a plugin – Web Analyzer

The tool seems to rely on node, so you need to install that as well. Also, it doesn’t look like it installs all of the necessary packages (at least it didn’t work for me, until I installed the packages). So, you may need to run npm install for these packages:
npm install -g eslint eslint-config-defaults
npm install -g babel-eslint

To config it, go to Tools – Web Analyzer – Edit ESLint Settings. All of the configuration settings can be found at For example, if you use Jasmine tests and jQuery, your “env” will look like this:
“env”: {
“browser”: true,
“node”: true,
“es6”: true,
“jasmine”: true,
“jquery”: true

In the “rules” block you can turn on/off individual rules and specify if they should show up as warnings (1) or errors (2).
“rules”: {
“eqeqeq”: 2,

This means that if ESLint sees “==” instead of “===” it will show up as an error in your Visual Studio Error List.

From .Net Developer to Elm. Part 2 – Making a Simple Project.

In this article I’ll write a simple Bayesian Calculator using Elm.
Link to final project – Bayesian CalculatorSource Code

Create a directory for your project.
cd into it.
Run “elm-make” to initialize a new elm project.
Install some packages for working with web:

elm-package install “evancz/elm-html”
elm-package install “evancz/start-app”

start-app takes care of some application wiring,”setting everything up so you can focus entirely on writing your app

If you open elm-package.json, you will see that the packages, which we just installed, were added to “dependencies” node.

I’ll use npm and gulp to manage my build. Also, I’m using bootstrap (cause css is hard)
npm init
npm install bootstrap –save-dev
npm install gulp –save-dev
npm install gulp-elm –save-dev
npm install gulp-rename –save-dev

The last piece of setting up is gulp. In the script, I just combine all css and js into bundles and copy them to dest folder.

We’re ready to start writing our app.

Create Calculator.elm. This is where our code will go.

Create Calculator.html. This will encapsulate resulting JavaScript file from Elm. Since I’m writing a full-screen application, all we have to do is add this to the script block:

var app = Elm.fullscreen(Elm.Calculator);

Now, to the application code.

Our model is quite simple – consists of four string fields related to four input fields on the form.
We have three inputs on the page – all encapsulated inside entryForm:

entryForm : Address Action -> Model -> Html
entryForm address model =
    [ class "form-horizontal" ]
    [ formGroupItem (priorProbabilityItem address model)
    , formGroupItem (hitRateItem address model)
    , formGroupItem (falseAlarmItem address model)
    , formGroupItem (resultItem address model)

formGroupItem is simply a method to produce another div with a class of “form-group”:

formGroupItem : List Html -> Html
formGroupItem body =
    [ class "form-group" ]

body in here is just a list of Html elements that we are passing to our div.

Let’s look at one of the inputs:

priorProbabilityItem : Address Action -> Model -> List Html
priorProbabilityItem address model =
  [ label
      [ for "priorProbability", class "col-md-3 control-label" ]
      [ text "Prior Probability" ]
  , div
      [ class "col-md-9" ]
      [ input
          [ type' "text"
          , placeholder "0.00"
          , value model.priorProbability
          , id "priorProbability"
          , autofocus True
          , Utils.onInput address UpdateInitialProbability

We have a label and a div with an input which maps to priorProbability field in our model.
Every time a user enters something we react to it by addressing UpdateInitialProbability action:

update : Action -> Model -> Model
update action model =
  case action of
    UpdateInitialProbability probability ->
      { model | priorProbability = probability }

In the code above we are updating our model with the new value that a user entered for priorProbability.
We have the same logic for all of the other input fields.

Every time a model changes, we try to show the Bayes calculation result:

resultItem : Address Action -> Model -> List Html
resultItem address model =
  [ label
      [ for "bayesResult", class "col-md-3 control-label" ]
      [ text "New Probability" ]
  , div
      [ class "col-md-9" ]
      [ span [] [ text (bayesResult model) ]

bayesResult is responsible for generating new probability. If some input is invalid, we just don’t display anything. Sure, validation could be a little more sophisticated, but we’re just trying it out.

While in development, make sure to run elm-reactor and gulp in the command line – open two tabs or windows (depending on your console app) for each one and just run “elm-reactor” in one, and “gulp” in another.

In order to see your app in a browser, go to http://localhost:8000/dest/Calculator.html
Every time you save your elm file, it should update the js files in the dest folder. You still have to refresh the browser to see the changes. I haven’t quite figured the auto-refresh part with gulp and elm.

If you want to see the build errors, they should show up in the console, which runs gulp command. Alternatively, if you use Sublime, press Ctrl + B to build it and all errors should show up directly in Sublime.

From .Net Developer to Elm. Part 1 – Elm with Sublime.

Elm is a an amazing way to build web applications that guarantees no runtime exceptions and blazingly fast rendering.
This is a path -one of many possible- to start Elm development.

Step One – Get the Right Tools.
Sublime is my editor of choice. Amazingly fast and extensible.

First, a few general tweaks

  • Enable Go to Definition on Ctrl + Mouse
    Create a new file – “Default (Windows).sublime-mousemap” – in %appdata%\Sublime Text 3\Packages\User
    With the following content:
    “button”: “button1”,
    “count”: 1,
    “modifiers”: [“ctrl”],
    “press_command”: “drag_select”,
    “command”: “goto_definition”
    More details on Linux and Mac here
  • Add a shortcut for locating a file in the file tree sidebar.
    Go to Preferences -> Key Bindings-User and add:
    { “keys”: [“alt+shift+l”], “command”: “reveal_in_side_bar” }
  • Pick a different theme, if you’d like – soda-theme.
  • Install Sublime Package Control to enable easy package installation – Package Control

Now, some Elm-specific changes.

  • Install Elm Language Package
  • Install elm-oracle to enable autocompletions.
  • Install Highlight Build Errors from Sublime Package Control
  • Install elm-format to enable auto-formatting. Just download the zip and add the executable to the path to make it work.
    To enable automatic formatting on every save, go to Preferences -> Package Settings -> Elm Language Support -> User, and add this setting: “elm_format_on_save”: true

When you work with elm files, you can press Ctrl+B to build it. If there are any errors or warnings, they will show up in the console below and also get highlighted.

If you want to see the definition of a method, press Alt+Up while your cursor is on the method.

What’s new JavaScript 2015/es6 (short summary)

  • let – block scope; no hoisting
  • const
  • Blocked scoped functions
        function foo () { return 1 }
        foo() === 1
            function foo () { return 2 }
            foo() === 2
        foo() === 1
  • Destructuring
    let foo = ["one", "two", "three"];
    let [one, two, three] = foo;
    console.log(one); // "one"
    console.log(two); // "two"
    console.log(three); // "three"
    let a = 1;
    let b = 3;
    [a, b] = [b, a];
    console.log(a); // 3
    console.log(b); // 1
    var expense = {
      type: 'Business',
      amount: '$40'
    const {type, amount} = expense;
    //Or use in functions:
    function({type, amount}){}
  • Defaults

    let hasDefaults = function(something = "default"){
    console.log(something); //default
  • Rest/Spread

    function sortRestArgs(...theArgs) {
      var sortedArgs = theArgs.sort();
      return sortedArgs;
    console.log(sortRestArgs(5,3,7,1)); // shows 1,3,5,7
    const defaultColors = ['red', 'green'];
    const extraColors = ['orange', 'blue'];
    [...defaultColors, ...extraColors]
  • Template literals

    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
    // "Fifteen is 15 and
    // not 20."
  • Arrow Functions

    let add = (a,b) => a+b;
    let sum = add(1,2);

    Also makes ‘this’ behave as you would expect it to behave.

  • Iterators and Generators
    for(let value of ["a", "b", "c"]){
    // "a"
    // "b"
    // "c"
    function* idMaker(){
      var index = 0;
        yield index++;
    var gen = idMaker();
    console.log(; // 0
    console.log(; // 1
    console.log(; // 2
    for(let value of idMaker()){
  • New Data Types

    var myMap = new Map();
    myMap.set(0, "zero");
    myMap.set(1, "one");
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    var mySet = new Set();
    mySet.add("some text");
    var o = {a: 1, b: 2};
    mySet.has(1); // true
    mySet.has(3); // false, 3 has not been added to the set
    mySet.has(5);              // true
    mySet.has(Math.sqrt(25));  // true
    mySet.has("Some Text".toLowerCase()); // true
    mySet.has(o); // true
    mySet.size; // 4
    mySet.delete(5); // removes 5 from the set
    mySet.has(5);    // false, 5 has been removed
    var wm1 = new WeakMap(),
        wm2 = new WeakMap(),
        wm3 = new WeakMap();
    var o1 = {},
        o2 = function(){},
        o3 = window;
    wm1.set(o1, 37);
    wm1.set(o2, "azerty");
    wm2.set(o1, o2); // a value can be anything, including an object or a function
    wm2.set(o3, undefined);
    wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
    ar ws = new WeakSet();
    var obj = {};
    var foo = {};
    ws.has(window); // true
    ws.has(foo);    // false, foo has not been added to the set
    ws.delete(window); // removes window from the set
    ws.has(window);    // false, window has been removed
  • Modules

    export let a ={};
    export let b =function(){};
    import {a,b} from c
  • Promises

        var p1 = new Promise(        
            function(resolve, reject) {
                    function() {
                    }, Math.random() * 2000 + 1000);
            function(val) {           
            function(reason) {
                console.log('Handle rejected promise ('+reason+') here.');
    //With fetch:
      .then(response => response.json())
      .then(data => console.log(data));
  • Class, constructors
  • class Test {
    class SubTest extends Test{
  • Array Helper methods


    let colors = ['red', 'blue', 'green'];
    colors.forEach(c => console.log(c)); 
    let numbers = [1, 2, 3];
    let doubled = => c * 2);
    let sum = numbers.reduce((sum, number) => sum + number, 0)
    let divisibleByTwo = numbers.filter(c => c % 2 === 0);
    let allDivisibleByTwo= numbers.every(c => c % 2 === 0);
    let someDivisibleByTwo= numbers.some(c => c % 2 === 0);
    let users = [ {name: 'Jay'},{name: 'May'},{name: 'Jay'} ]
    let jay = users.find(u => === 'Jay')
  • Enhanced Object Literals

    function test(someValue)
        return {
          someValue: somevalue,
          someFunction: function(){}
    Is now equivalent to 
     function test(someValue)
        return {

Some great resources on es6 – and

Functional Extensions for C#


public static TResult Map<TSource, TResult>(
	this TSource @this,
	Func<TSource, TResult> fn) => fn(@this);


public static TResult Tee<t>(
	this T @this,
	Action<T> fn) => fn(@this)
		return @this;

Partial Function Application

public static Func<int, int> Add(int x) => y => x + y;
new[] {1, 2, 3}.Select(Add(1))

More stuff like this in Dave Fancher PluralSight course Functional Programming with C#

Short Summary of Delegation in C#


public delegate decimal MathOp(decimal left, decimal right)

public static decimal Add(decimal left, decimal right)
	return left + right;
private static MathOp GetOp(char op)
	switch (op)
		case '+': return Add;


public interface IMathOp
	decimal Compute(decimal left, decimal right);

public class AddOp : IMathOp

	decimal Compute(decimal l, decimal r)
		return l + r;

private static MathOp GetOp(char op)
	switch (op)
		case '+': return new AddOp();

Anonymous Methods

public delegate decimal MathOp(decimal left, decimal right)

private static MathOp GetOp(char op)
	switch (op)
		case '+': return delegate (decimal l, decimal r) { return l + r};

Generic Delegates and Lambda Expressions

public static Func<decimal, decimal, decimal> GetOp(char op)
	switch (op)
		case '+': return (l, r) => l + r;

For complete details, see Dave Fancher PluralSight course Functional Programming with C#