Strongly-typed front-end: experiment 2, simple application, in Elm

Contents

  1. Introduction
  2. Experiment 1, hex2rgb
  3. Experiment 2, simple application

(Heavily over-opinionated statement) Elm forces you to handle error scenarios when writing the code.

Sandbox

This is pretty much a translation of a TypeScript code from above:

module Main exposing (..)

import Browser
import Html exposing (Html, button, div, text, input, select, option)
import Html.Attributes exposing (value)
import Html.Events exposing (onClick, onInput)

-- util

type Shape = Circle | Square

calculateArea : Shape -> Float -> Float
calculateArea shape value =
  case shape of
    Circle -> pi * value * value
    
    Square -> value * value
    
-- MAIN

main =
  Browser.sandbox { init = init, update = update, view = view }

-- MODEL

type alias Model = { shape: Shape, value: Float, area: Float }

init : Model
init = { shape = "", value = 0, area = 0 }

-- UPDATE

type Msg
  = ShapeChanged Shape
  | ValueChanged Float
  | CalculateArea

update : Msg -> Model -> Model
update msg model =
  case msg of
    ShapeChanged shape ->
      { model | shape = shape }

    ValueChanged value ->
      { model | value = value }
      
    CalculateArea ->
      { model | area = (calculateArea model.shape model.value) }

-- VIEW

onShapeChanged : String -> Msg
onShapeChanged shape = 
  case shape of
    "circle" -> ShapeChanged Circle
    "square" -> ShapeChanged Square

onValueChanged : String -> Msg
onValueChanged value = ValueChanged (Maybe.withDefault 0 (String.toFloat value))

view : Model -> Html Msg
view model =
  div []
    [ select [ onInput onShapeChanged ] [ 
      option [ value "" ] [ text "Choose shape" ], 
      option [ value "circle" ] [ text "Circle" ],
      option [ value "square" ] [ text "Square" ] ]
    , input [ value (String.fromFloat model.value), onInput onValueChanged ] []
    , button [ onClick CalculateArea ] [ text "Calculate area" ]
    , div [] [ text ("Area: " ++ (String.fromFloat model.area)) ]
    ]

Note that it won’t compile:

-- TYPE MISMATCH ----------------------------------------------- Jump To Problem

Something is off with the body of the `init` definition:

29| init = { shape = "", value = 0, area = 0 }
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The body is a record of type:

    { area : Float, shape : String, value : Float }

But the type annotation on `init` says it should be:

    Model
Read more

Strongly-typed front-end: experiment 2, simple application, in PureScript

Contents

  1. Introduction
  2. Experiment 1, hex2rgb
  3. Experiment 2, simple application

In PureScript world there are quite a few libraries for React. And all of them have terrible (or rather non-existent) documentation, so I had to use as much intuition as outdated and barely working code samples. In this case I have picked purescript-react-dom.

Initial application structure:

module Main where

import Prelude

import Control.Monad.Eff

import Data.Maybe
import Data.Maybe.Unsafe (fromJust)
import Data.Nullable (toMaybe)

import Effect (Effect)
import Effect.Console (log)

import DOM (DOM())
import DOM.HTML (window)
import DOM.HTML.Document (body)
import DOM.HTML.Types (htmlElementToElement)
import DOM.HTML.Window (document)

import DOM.Node.Types (Element())

import React

import React.DOM as DOM
import React.DOM.Props as Props

type Shape = Circle | Square

calculateArea :: Maybe Shape -> Float -> Float
calculateArea Nothing _ = 0
calculateArea (Just Circle) value = pi * value * value
calculateArea (Just Square) value = value * value

getShape :: String -> Maybe Shape
getShape "circle" = Just Circle
getShape "square" = Just Square
getShape _ = Nothing

onShapeChanged ctx evt = do
  writeState ctx { shape: getShape ((unsafeCoerce evt).target.value) }

onCalculateAreaClicked ctx evt = do
  { shape, value } <- readState ctx
  writeState ctx { area: calculateArea shape value }

areaCalculator = createClass $ spec { shape: Nothing, value: 0, area: 0 } \ctx -> do
  { shape, value, area } <- readState ctx
  return $ DOM.div [] [
    DOM.div [] [
      DOM.select [ Props.onChange (onShapeChanged ctx) ] [
          DOM.option [ Props.value "" ] [ DOM.text "Select shape" ],
          DOM.option [ Props.value "circle" ] [ DOM.text "Circle" ],
          DOM.option [ Props.value "square" ] [ DOM.text "Square" ]
      ],
      DOM.input [ Props.value (show value) ] [],
      DOM.button [ Props.onClick (onCalculateAreaClicked ctx) ] [ DOM.text "Calculate area" ]
    ],
    DOM.div [] [
      DOM.text ("Area: " ++ (show area))
    ]
    ]

main = container >>= render ui
  where
  ui :: ReactElement
  ui = createFactory areaCalculator {}

  container :: forall eff. Eff (dom :: DOM | eff) Element
  container = do
    win <- window
    doc <- document win
    elt <- fromJust <$> toMaybe <$> body doc
    return $ htmlElementToElement elt
Read more

Rogue bomber

This is a yet another show-off blog.

Yet another one-day-build, made specifically for not-so-exciting ShipIt-51 hackathon we are having at work right now.

This is a terrible code written in JS in matter of some 8 hrs.

Click the button below to start playing.

Gantt chart. Part 3

Contents

I have been writing about and improving on my Gantt chart implementation for quite some time now.

It all started with this (blog):

First revision of Gantt chart

Then I added few features (blog):

Second revision of Gantt chart

Back then I have promised to re-write the implementation in Canvas. And so I did.

Curious fact: I did not plan on doing this at this time - it was a private email from darekeapp12 who wrote this:

I have looked at your blog for Gantt chart and implementation. I am doing a project using React and Node/Express and need to implement Gantt chart that is also draggable i.e. the bars can be moved and also resized from either end. I have researched heavily but could not find anything. I am thinking if there is no library, something could be built from scratch.

The sender seemed dodgy (DAREKE app) so I did not want to reply to avoid unnecessary spam subscriptions, but I was happy to improve my old project.

Here are few new features and improvements added to the chart:

  • scrolling and zooming in & out is now a thing
  • you can drag the milestones around and stretch & shrink them
  • an event will be fired whenever a milestone is changed (moved / stretched / shrinked)
  • dependencies are now typed: start-to-start, end-to-end or end-to-start are the only supported types

Here, you can even play around with it now!

More about the implementation specifics under the cut.

Read more

ShootThem! revival

Quite some time ago I dag out the sources of an old game of mine, ShootThem! made back when I was at high-school, around 2006.

It has been over a decade ever since I made that game and I had enough inspiration to revisit the code once again.

This is a short update blog about what it used to be and what it became as of now.

Read more

Erlang example 2.0

Quite some time ago I've published a blogpost about Erlang. It claimed to present a short intro to distributed programming in Erlang. But it turned to be a very simple communication application, nothing super-exciting.

In this post I would like to elaborate more on the topic of Erlang, for a number of reasons:

  • it is a pretty simple language itself
  • the distributed systems topic gets more and more of my attention these days
  • when I was looking at Erlang, I would love to see a more advanced tutorial myself (more practical things and more Erlang platform features showcased)
Read more

Vim keystrokes cheatsheet

The time has come for me to list few of the commands and keystrokes that I use (and the ones that I don't but would like to start) in Vim.

I am actually running a Vim plugin for Visual Studio Code (this and the previous blogs are actually written with this plugin ON) at this very moment.

Bear 🐻 in mind: this blog is aboout keystrokes only, it is not about plugins or configuration I use - I shall cover that one day.

Things I know by heart

  • h, j, k, l for slow but precise character-wise movement
  • w, b for faster forward (and, correspondingly) backward word-by-word movement
  • $ and ^ to go to the last and first word character of the line
  • gg and G to go to the beginning and the end of the file
  • O (capital o) to create a blank line and go to INSERT mode above and below (lower-case o) the cursor
  • f, F and t and T for single character lookup within the current line
  • / and ? to search forwards and backwards
  • c (followed by the object) to change the object; this expands to the following few commands:
    • cw to change the current word under cursor
    • cit to change the text within the current XML tag
    • ca' to change the text surrounded by single quote
    • ci< to change the text surrounded with &lt; and &gt;
    • ci{symbol} to change the text surrounded by symbol, which could be ', ", &#96;; you can also use b( for block of text, surrounded by braces, B{ for block of text surrounded by curly braces or p for paragraph, all instead of symbol
  • v to enter the VISUAL mode, followed by the command:
    • v{select}c immediately change the selection
    • v{select}d cut the selected text
  • y and p copy and paste the selected text (lower-case p pastes above the current line, capital-case P pastes below; capital-case Y copies the entire line, so the duplicate line command in Vim is Y, P)
  • {number}{command} repeat the command number times
  • . (the period or dot symbol) repeats the last command
  • x to remove the character under cursor
  • r{char} to replace the character under cursor with char
  • A to go to the end of the line and enter INSERT mode ("append")
  • u and Ctrl+r to undo and redo actions
  • > and < adds or removes the indentation

Things that I am still getting used to

  • {number}{motion} instead of h, j, k, l
  • a instead of i to enter INSERT mode after the cursor (as opposed to i which enters INSERT mode before the cursor)
  • H, M and L to go to the top, middle and the bottom of the screen (High, Mid and Low)
  • * and # to search for the word under cursor forwards and backwards
  • {count}/{query}⏎ to go to the count-th occurrence of query; it is same as searching with / and then hitting n count times
  • gd navigates to a definition of an entity under the cursor
  • gf navigates to the path under cursor
  • % moves the cursor to the matching brace, bracket or curly brace
  • g~ toggle the case
  • = format the selection
  • gU makes the selection uppercase

Gantt chart with D3. Part 2

Contents

In the original blog I claimed to implement something like this:

Yet I ended up implementing something more like this:

Does not look quite same, right? It also does not work quite same and lacks few quite important features too.

Don't get me wrong, the original implementation did serve project needs, but it was not something anybody could simply use in their project management software and expect customers to love it.

Hence I came up with these complaints about the implementation:

Namely, there are three main issues that I see:

  1. there is a place for mistakes: milestones are allowed to depend on later milestones or simultaneously going ones
  2. there is no clear distinction between the dates each specific milestone starts or ends
  3. if the milestones overlap with current timeframe, current day is not highlighted on the chart (and that often is useful)

Apart from that, there are few technical challenges preventing his whole thing from becoming a real application component:

  • dependency lines look ugly with those sharp corners
  • the implementation is not based on any framework neither does it declare its dependencies (like D3 or MomentJS)

Now I want to revise the original implementation and make it a bit more usable, just like this:

Read more

Erlang in 5 minutes

X = erlang, Y = 5, io:format("Learn ~s in ~s minutes", [ X, Y ]).

Welcome to a 5-minute Erlang introduction!

First things first:

  • Erlang is a functional programming language
  • erl is the REPL shell
  • Ctrl + G and then q or q(). to exit the shell
  • c(file_name). to load the code from file

Now, to the language constructs:

  • every statement has to end with a dot (.) symbol
  • multiple statements are separated by comma (,) character
  • constants start with a Capital Letter
  • atoms (yes, like in Ruby) start with lowercase letter
  • atoms are allowed to contain spaces (sic!), but then they have to be quoted: 'atoms are awesome'
  • atoms can also have the at sign (@)
  • anonymous functions are defined as fun() -> return_statement end.
  • last statement before end must not end with comma
  • function signature is function_name/number_of_arguments: factorial/1, format/2
  • comments start with percent (%) symbol
  • lists are [ TheOnlyElement ] or [ Head | TailElements ], where TailElements is also a list
  • pattern matching just works [ Head1 | Head2 | Tails ] = [ 1, 2, 3, 4 ]
  • strings are just "strings"
  • tuples are quirky { elt1, elt2 }
  • maps are even weirder #{ key => value }
  • operators are almost fine:
    • comparison: < (less than), > (greater than), >= (greater than or equals to), =< (equals to or less than), == (equals to), /= (not equals to), =:= (adds type checking on tops, JS equivalent of ===)
    • assignment / pattern matching: =
    • math: +, -, *, /, div, rem (Pascal way)
    • typechecking: is_atom/1, is_function/1, is_number/1, is_boolean/1, is_pid/1, is_list/1, etc.
  • list comprehentions are similar to lists: [ N || N <- [ 1, 2, 3, 4, 5 ], N rem 2 == 0 ].
  • files are modules, defined with few statements:
    • -module(module_name).
    • -export([ list_of_function_signatures ]).
    • -import(module_name, [ list_of_functions ]).
  • calling module's export be like module_name:function_name(arguments).

Quick recap:

%%% module comment
-module(erlang_example).

% exporting the functions from the module
-export([ factorial/1 ]).

% importing the functions from the other module
-import(my_other_module, [ new_factorial/1 ]).

% constants with pattern matching - will assign the value to non-defined constant on success
X = 5.

% redefinition is prohibited
X = 10. % exception

% functions can also be constants
PlusOne = fun(X) -> X + 1 end.

% or, multiline
PlusTwo = fun(X) ->
  X + 2

  end.

% the standard way
bad_factorial(N) ->
  N * factorial(N - 1).

%% function documentation
% functions can have *guargs*, which are basically pattern matching
% also, function overloading is split with semicolon (;)
factorial(N) when N =< 1 -> 1;

% last overload ends with dot (.)
factorial(N) -> N * factorial(N - 1).

% some return types
string_fn() -> "hello, world!".

list_fn() -> [ 1, "elements could be of different types too", -3.14, atom ].

function_function() ->
  fun(X) -> X mod 2 end.

dict_fn() -> #{ "key" => -3.14 }.

tuple_fn() -> { elt1, elt2, "elt 3" }.

%% note how overriden_function/1 has different definition than overriden_function/2
overriden_function(List) ->
  overriden_function(List, 0).

% the power of pattern matching!
overriden_function([ Head ], Acc) -> Acc + Head;

overriden_function([ Head1 | Head2 ], Acc) -> Acc + Head1 + Head2;

overriden_function([ Head | Tail ], Acc) ->
  overriden_function(Tail, Acc + Head);

overriden_function([], Acc) -> Acc.

complex_function(A, B) when A =< B -> A;
complex_function(A, B) when A > B -> B.

complex_function(A, B, C) ->
  X = complex_function(A, B),
  complex_function(X, C);

complex_function(A, B, C, D) ->
  X = complex_function(A, B),
  Y = complex_function(C, D),
  complex_function(X, Y).

fst({ First, _ }) -> First.

snd({ _, Second }) -> Second.

evens(List) -> [ X || X <- List, X rem 2 == 0 ].

keys(#{ Key => Value, _ => _ })

There also are few good resources on this: [https://learnxinyminutes.com/docs/erlang/](Learn X in Y minutes (where X = erlang)) and [http://erlang.org/doc/apps/inets/http_client.html](Official Erlang docs).

A response to response to hello world

Recently I've received an email from StackOverflow newsletters with a link to a quite controversial (at first glance) blog, A response to Hello World by Caleb Doxsey. This blog is a response to another curious read, Hello world by Drew DeVault.

In the former article, author compared the performance of a tiny "Hello, World" program in Assembly to the same program in Go. He then tried to optimize the program in Go to run faster and towards the end of an article comes up with a program that is faster than its Assembly counterpart.

And this totally makes sense, since if you give it a good read, you will notice that author did optimize the program in Go but did not do that for the Assembly program.

I have decided to burn few hours of my life and jump onto this topic, since, in my opinion, author did not do a fair comparison.

Read more