Getting started with Elm-Webdriver

March 3rd, 2017

Today I tried to add elm-webdriver to my elm project (on Ubuntu 16.04). It wasn’t as easy as the instructions make out. So I updated the instructions. Read the rest of this entry »

Minimal elm program

February 8th, 2017

This is not the shortest Elm hello world program. But it is about as short as I can make an Html.program. Having written it, and read it, it felt somehow profound. Like a haiku.

module Main exposing (..)

import Html exposing (..)


main =
    Html.program
        { init = () ! []
        , update = (\_ a -> a ! [])
        , view = (\_ -> h1 [] [ text "Hello World" ])
        , subscriptions = (\_ -> Sub.none)
        }

Elm Cambridge first meetup: an overview of Elm

February 6th, 2017

Here are the Prezi ‘slides’ from my talk tonight at the first Cambridge Elm meetup

Elm support compiled into Universal Ctags

February 6th, 2017

I started this project to make vim-tagbar work with Elm. I use tagbar to get an overview of my source files (especially python); I like how it presents the scope of nested tags. I wanted that overview of my Elm modules too. ctags-elm got me started but exuberant ctags doesn’t let you define scoped tags in config files. Universal Ctags does. So now, after some discussion, the Ctags part of vim-tagbar-ctags-elm is a Universal Ctags optlib. Optlib lets you define a set of command line options in a file, and then generate c source from them so they ca be compiled into ctags executable.

This was always in the plan. Next tagbar itself, maybe?

A ‘Phone Romance

July 27th, 2016

a-phone-romance

Thinking in Elm (and not cutting corners)

July 10th, 2016

So, I’m processing this list of js data which, for this evening, I know
contains exactly one thingummy. I’m I want to wire up some Elm and get things
to type check before I start to worry about handling lists of different sizes.
Calling upon my conventional (python) wisdom, I set about processing the
singleton in the list.

  case msg of
    UpdateThing msg' ->
    (thing, cmd) = Thingummy.update msg'  ... singleton element from model.things ...

How do I get that sucker? I’m thinking python: `model.things[0]` but, of
course, both `model.things !! 1`, and `List.head` return `Maybe a`. So now I’m
going:

    ... (thing, cmd) ... = Maybe.map (Thingummy.update msg') (List.head model.things) ...

But now the lhs pattern is wrong, I’m using `map` and, ultimately, I need to
turn that updated singleton back into a list anyways.

  case msg of
    UpdateThing msg' ->
    (things, cmds) = List.unzip (List.map (Thingummy.update msg') model.things) 

Job done. (I should qualify that the job here is just the quick hack for
my singleton list. It’s applying the same change to all elements)

Moral: it isn’t any less complex to deal with a list of things than
with a thing taken from a list (Maybe). I can’t ask Elm to accept my
assumption that a list will contain exactly one item. Elm wants me to model
it. If there’s exactly one, just use a variable. If there’s zero or one,
use Maybe. Or just use a list, it’s just as simple!

The Fridge-brilliance of Maybe

May 30th, 2016

I’ve been tinkering with Elm recently. It’s a typed functional programming language that reminds me of the Haskell I wrote during my PhD. And, it’s great fun. I wrote a toy application, and recently upgraded it to 0.17. Along the way I had an insight about the Maybe type which I try and to explain in context.

My generic text input field needs to be able to respond to the Enter and Escape keys by triggering Latch and Reset messages respectively.

My onKeyDown function generates an on-keydown handler attribute that maps Int key codes to messages.

onKeyDown : (Int -> msg) -> Attribute msg
onKeyDown mapping =
    on "keydown" <| Json.map mapping keyCode

This excerpt from my view function shows how I use it; I define enter and escape as constant functions, Latch and Reset are constructors from my Msg type:

view model =
    ...
    div []
	[ input
	    [ type' "text"
	    , highlightStyle
	    , placeholder model.name
	    , value model.input
	    , autofocus True
	    , name model.name
	    , onInput UpdateInput
	    , onKeyDown
		&lt;| keyMsg
		[ ( enter, Latch )
		, ( escape, Reset )
		]
	    ]
	    []
	]

The helper-function keyMsg takes a list of pairs (in lieu of literal dict syntax) from which it builds a dict of key codes and the corresponding messages

keyMsg : List ( Int, Msg ) -> Int -> Msg
keyMsg mapping keycode =
    Dict.fromList mapping
        |> Dict.get keycode
        |> Maybe.withDefault NoOp

Now we get to the interesting part. While writing this I wondered how to return the default value NoOp if the key code isn’t in the dictionary. In python, dict.get(key [, default]) lets you specify the default, so I started looking in the dict module. But it isn’t there. It’s in Maybe.

At which point I saw the Fridge Brilliance of Maybe. Putting the default behaviour inside dict.get means it has to be duplicated in any other data structures that require default behaviour. Making it part of Maybe demonstrates why Maybe so much more than just an abstraction of pointers that might be null. It is the right place to define default-value behaviour.

Edit!

If I bring the names into scope, keyMsg function shortens nicely like this:

keyMsg mapping keycode =
    Dict.fromList mapping |> get keycode |> withDefault NoOp

Whoa! Even more brilliance with the ? operator!

keyMsg mapping keycode =
    Dict.fromList mapping |> get keycode ? NoOp

Get list of worksheets on the command line

April 14th, 2016

Today I need to get a list of worksheets from a very large spreadsheet (~100 worksheets, many thousands of cells on each) quickly from the command line. My ruby script tried to parse the entire workbook and exploded all my RAM. Then I discovered grep -0 which prints matching occurrences only (each on a separate line) which is very useful with regular expression patterns. The “sheet name” entries are in the “workbook.xml” zipped up in the Excel file.

$ unzip -c your-large-spreadsheet.xlsx xl/workbook.xml | grep -o sheet\ name=\"[^\"]*\" | cut -d = -f 2

Getting round the limitations of Excel VBA’s UsedRange function

April 5th, 2016

Turns out that the Excel VBA function UsedRange doesn’t always give the expected results. It gives you the range of cells that have ever been used. If you’ve formatted them, or they used to have values in that you’ve since deleted, you still get those cells. Today I wanted to iterate all cells in a lot of sheets. Some of those sheets had lots of cells in their UsedRange. I hit upon a solution I’ve not seen anywhere else: take the union of constants and formulas in a sheet. This  is quick, because you can use SpecialCells to do the heavy lifting. And you can refine the results to exclude errors using SpecialCells Value argument (the default 23 below selects everything). Here’s the code

Function myUsedRange(ws As Worksheet, Optional lookfor As Long = 23) As Range
    Dim c As Range, f As Range
    On Error Resume Next
    With ws.Range("A1")
        Set c = .SpecialCells(xlCellTypeConstants, lookfor)
        Set f = .SpecialCells(xlCellTypeFormulas, lookfor)
        If c Is Nothing Then Set c = .Cells
        If f Is Nothing Then Set f = .Cells
    End With
    Set myUsedRange = Union(c, f)
End Function

This returns a non-contiguous range containing only the cells you want. This version is a bit lazy and includes [A1] if there are no constants or no formulas matching your search. I didn’t mind because I was using lookfor=2 to search for text which reduced the number of cells by thousands. Hundreds of thousands in some cases. A better version would take a default as a parameter and return it only if neither  constants or formulas gave any results.

pip install rx

March 22nd, 2016

I just installed RxPy the Reactive extensions for Python, as you may guess from the title of this article. Well, that was easy. What next? Here’s a delightfully short program which does — ahem — something:

import sys
import rx

rx.Observable.from_(sys.stdin).subscribe(print)

It echoes stdin to stdout. Kinda.

  • There are more newlines than I was expecting — an extra one after each line is echoed
  • The single line is actually an expression returning a Disposable that you can use to unsubscribe. I’m discarding it.
  • I have syntastic installed in Vim and pylint complains of a syntax error when I pass print to subscribe so perhaps I need to configure it to know about python3.