Partial Function Application In Elixir

So I’m trying to fill out my understanding of basic functional programming concepts in terms of Elixir and Erlang.  One concept that I wanted to know a bit more about is how Partial Function Application and Currying work in Elixir.  Especially given that the function signature of a function in Elixir includes its arity, it seems somewhat unlikely that Elixir would support currying and/or partial function application.  But a little bit of hacking turned up a nice surprise.  While Elixir may not support currying (I really cannot tell if it is supported or not) it does support partial function application which seems to be the main reason to concern one’s self with currying anyway.

Partial Function Application With Lambdas


multiply = &(&1 * &2)

timestwo = &(multiply.(&1,2))

Interestingly, using this technique you can set any number of parameters to a fixed value.  Consider this:


multiply4 = &(&1 * &2 * &3 * &4)

times20 = &(multiply4.(&1,&2,5,4))

Lest I be misunderstood, I wouldn’t advocate writing code like that; I’m just saying that it’s possible to do.

Partial Function Application With Modules


defmodule PaTest do
  def f1(n, m) do
    n * m
  end

  def f2(m) do
    f1(3,m)
  end
end

I hope this may save someone a bit of work.

Configuring Elixir For Development

One of the more exciting new functional languages of the last couple of years is a marriage of Erlang and Ruby called Elixir.  Besides adding an arguably better syntax with which to program the Erlang VM (also known as the BEAM VM), Elixir adds meta-programming, addresses issues Erlang had with dealing with Unicode strings, and adds few other nice touches.  It’s nice icing on the Erlang cake.  Joe Armstrong, the creator of Erlang, has gone on record as endorsing Elixir. I leave it to those who are interested in reading Mr. Armstrong’s comments to read for themselves; tl; dr he likes Elixir just like he likes Erlang.

So I’ve been wanting to play with Elixir for a while and when I want to play with a new language, I often configure a quick command prompt set up with the proper development environment.  It’s halfway between creating a new VM and not doing anything special. So if others care to build an elixir command prompt, here are the steps.  Note that you can stop before installing Elixir and have a great Erlang environment to play around with.

1.) Install Erlang. You can download a nice Windows installer package for Erlang from Erlang Solutions.

2.) Once erlang is installed, you’ll want to grab the prebuilt zip of Elixir from the Elixir GitHub repository.

3.) Create a powershell script to configure the environment.  Here’s mine:

Set-Variable -Name elixirBase -option Readonly -value "C:/dev/elixir_0.12.4"
Set-Variable -Name erlangBase -option Readonly -value "C:/Program Files/erl5.10.2"
Set-Variable -Name gitPath -option Readonly -value "c:/program files (x86)/git"

$env:Path = "$erlangBase/bin;$elixirBase/bin;$gitPath/bin;"

Set-Variable is the Powershell analog of setting an environment variable.  $env:Path is the actual Path environment variable in this case.  Since the environment will only apply for the duration of the Powershell session, I simply replace the existing Path with one set up specifically for the Elixir/Erlang combo. I named the file ElixirSetup.ps1; it’s convention for Powershell scripts to have a ps1 extension.  NB: These paths are on my machine and they’re for a slightly older version of Erlang (as of this writing current version installs to elr5.10.4).

Basically if I’m going to do a command prompt on Windows, Powershell is the way to go.  It remedies countless failings of the old cmd shell.

4.) Create a new shortcut with the following command line:

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -File C:\Users\Onorio_Development\Documents\WindowsPowerShell\ElixirSetup.ps1

Obviously you’ll want to replace these values with the correct values for your particular machine.

Once you get the shortcut set up and going, there are a few things to test.  You can run the Erlang REPL by typing erl at the command prompt.  You can test the Elixir REPL by typing iex.bat at the command prompt.  You have to type the entire name (with the .bat extension) due to there being an iex alias present in Powershell.

Elixir includes a nice little project management tool called mix which was inspired by Clojure’s Leiningen.  Mix basically lets you create a small skeleton of an Elixir project complete with a .gitignore file and a README.md as well as a skeleton unit test.

I hope others will consider this an invitation to start playing with Elixir and learning more about both Elixir and Erlang.

EDIT:

One annoyance that I discovered after I wrote this post is that the native Powershell terminal doesn’t support ANSI escape sequences.  IEx uses ANSI escape sequences and this is a real annoyance.  So I did some digging and found that ConEmu has nice support for ANSI and it remedies the issue with IEx very nicely.  There are other ways of getting support for the ANSI escape sequences as well but this is a nice robust remedy for the problem.

I Am Tired Of Swimming Against The Current

I have been a vocal advocate of F# for a long time. I’ve shared some of my little interesting discoveries in the language from time to time. I’ve been trying to help other .Net developers to see what a great, cool language F# is. I’ve tried to add intelligent conversation to the world although I have a bad habit of speaking before I think; I’ve been holding off on saying this for a while exactly because I do have a bad habit of speaking before I think. But this has been coming for a while.

I am just tired of seeing such a great technology being bungled by Microsoft.  I don’t know what the internal politics are and I don’t much care.  This has been coming for a while for me and today I finally reached the breaking point.

It started when I saw that the C# team rebuilt async functionality in C# 5.  I had always been told that Microsoft’s position was to encourage people to use C# where it made sense and to steer people to F# where F# made better sense.  The addition of async functionality to C# 5 shows that is simply a lie.  No matter what they do to C#, async will be easier to code in F#.  Yet rather than encouraging people to build their async code in F# and then link the libraries, the decision was made to build async into C#.  That disturbed me but at the time I thought to myself–oh well.  Now I am beginning to wonder if F# is being used as a way of prototyping ideas that Microsoft wants to pull into C#.

Then there were the conferences.  I went to LambdaJam in July.  There were maybe 30 or so of us who like and use F#.  There were probably easily 100 who like Clojure and probably a just slightly smaller number for Scala.  There were even folks interested in Erlang and Elixir–and I’m pretty sure there were more than 30 of them.

When I went to Strange Loop a few years ago–several sessions on Clojure, a few sessions on Scala, and one session on F#.  Just one poorly attended session given by one of the guys from the MS F# team.  Nothing speaks to Microsoft’s apathy regarding F# any louder or any clearer.

I tried leading a BOF for F# at CodeMash in 2011 as well.  Two people showed up.  Well two if you count me.  Don’t get me wrong; no doubt F# is starting to gain some traction.  F# is finally starting to gain some popularity.  But Clojure, Scala and Erlang are also gaining in popularity as well.

I don’t feel the need to follow the herd but I am also aware that if everyone is going in one direction there’s a good possibility that they’re all right and I’m the one that’s wrong.  That sounds like a statement of the obvious now that I reread it but I’ll leave it in anyway.

I’ve been waiting to see if  maybe the open source community might embrace F#.  F# is really a good language and I want to see it succeed.  But the open source community for F# is basically the same small set of people that have always worked with F#.  And somehow I don’t believe they will embrace F# any more than they’ve ever embraced Mono because they’ve grown up with “Microsoft is evil!” drummed into their heads.

So today someone for whom I have a great deal of respect basically told me to not criticize Microsoft for their apathetic approach to F# and that we as a community need to do more to push F#.  I guess those two conferences I organized here in Detroit and that F# user group I ran for a while just demonstrate what a slacker I am.  I guess the F# talks I’ve given basically show that I need to do much more for F#.  David Giard, Microsoft C# MVP once referred to me as a “F# Fanboy” (he was kidding but only a little) but apparently that’s simply not enough.

So to sum up; I’ve had it.  I’m going to learn Scala.  I know a few decent folks in the Scala community and I have no doubt that the fundamental ideas of functional will transfer just fine to Scala.  But I’m tired of fighting for F#.  Tired of fighting the tide of apathy coming from Microsoft.  I guess those folks who are fighting for F# within Microsoft  just don’t know how to fight the politics of Redmond.

I am only bothering to share this with the world because I have been a vocal advocate of F# in a lot of forums.  I hate the taste of crow but I hate being a hypocrite even more. Either way I’m not wasting any more of my time on the betamax of .Net languages.  I sincerely wish good luck to those sticking with F#; they’re a great, smart bunch tilting at windmills as they are.  As for me, I’m just tired of fighting for F# only to be told I’ve not done enough.  I really hope they succeed but they really have a tough course to chart because MS doesn’t seem to care at all about F# and I think the OSS community only sees evil Microsoft and they’re not willing to look beyond that.

 

Slick Use Case For Active Patterns

So I love it when a very natural use case arises for a feature that I want to practice.  I’ve been trying to better my understanding of active patterns lately and today I found a great use for them.

I’m fetching json data from a REST endpoint.  Of course I get back a string.  And the string contains some very specific text when there’s a problem processing the request on the server side.  So I ended up doing something like this:


let errResult = "Error creating user"

let (|ContainsErrString|) (stringToTest:String) = stringToTest.Contains(errResult)

//And further down in the code:

let res = sr.ReadToEnd()

let u1 =
 match res with
 | ContainsErrString true -> None
 | _ -> Some(JsonConvert.DeserializeObject<user>(res))

Simplifies the code dramatically and hides detail that the match doesn’t need to know about.  Terrific use case for an active pattern.

F# Tip Of The Week (14 October 2013)

It is possible to declare a list or an array without the separating semicolons by declaring each element on a separate line.  Like this:

let favoriteBreeds = [
    "Antwerp"
    "Carneaux"
    "Swiss Mondaine"
]

//Array

let favoriteBreedsArray = [|
    "Antwerp"
    "Carneaux"
    "Swiss Mondaine"
|]

Note: for reasons I confess are unclear to me, the first member of the list/array must be on the next line from the opening symbol of the collection. Well, to be precise (this is software development after all) this is true of arrays–the same is not true of lists. But since putting the first element of the array on the next line works in both cases, it’s simplest just to do it this way.

EDIT: Per Dave Thomas, you can put the first element of the collection on the same line as the opening symbol; you just need to insure that you align all of the other elements, DIRECTLY beneath the first element, as in this code gist which Dave put up.

Personally I consider it’s easier to simply stick to the convention of always putting the first element on the next line so you don’t have to worry that much about the alignment but this does work.

 

Functional Programming Makes Simple Easy

I do love the fact that F# (and functional programming in general) gives a developer the tools to make it easy to build simple code.
I was hacking together a function to convert a DateTime to a Unix Time Stamp (for using with the Meetup Restful API).  This was my initial pass at it:
    let unixTimeStamps startDate endDate=
        let startOfEpoch = new DateTime(1970,1,1)
        let startTS = uint64 (startDate - startOfEpoch).TotalMilliseconds
        let endTS = uint64 (endDate - startOfEpoch).TotalMilliseconds
        (startTS, endTS)
(BTW that may not be the exact working code but it should give the idea.)
Then I thought to myself–why should I return a tuple?  If I simplify the function to simply convert a DateTime to a UTS, I can just call it twice.  So I got this:
    let unixTimeStamp d =
        let startOfEpoch = new DateTime(1970,1,1)
        uint64 (d - startOfEpoch).TotalMilliseconds
Simpler but still not as simple as I could make it.  I was bothered by the fact that I had to truncate the decimal part of the returned timespan.  I had to truncate it because Meetup’s API balks at a time span with a fraction on the end of it.  So I modified the function one more time to make it both simpler and more generic:
    let unixTimeStamp d =
        let startOfEpoch = new DateTime(1970,1,1)
        (d - startOfEpoch).TotalMilliseconds
And I added a little function composition to handle Meetup’s little quirk:
    let fixUnixTimeStampForMeetup = unixTimeStamp >> uint64
At any rate, this is part of the reason I’ve got such a crush on FP and F#.  It does make it easy to build simple, reusable but still generic code.