Railway Oriented Programming In Elixir

A while back Scott Wlaschin posted a great blog post on what he called “Railway Oriented Programming.”  It’s a great treatment of a common problem in adopting functional programming; how to handle a chain of functions when one of the functions in the chain may return an error.  Of course stopping the chain when the first error is returned isn’t a difficult issue; the difficulty arises in structuring the code such that the code can continue running all the functions until and unless an error is encountered.  It’s a great read and a powerful idea.

So today someone asked a question on StackOverflow about how to accomplish basically that same idea in Elixir.  A little tricky to translate Scott’s ideas to Elixir because in his article his code is specified in F# and he created a special type to capture the success or failure of a function. F# is statically typed; elixir is dynamically typed which is, of course, a substantial difference.

At any rate, I saw the question and didn’t see that Saša Jurić had already posted a great answer.  So I posted my answer and then noticed his.  I mention this because I want to be clear; I wasn’t trying to steal anyone’s thunder or trying to enhance my rep or anything like that.  I just got excited; “hey, I know the answer to that question!” so I just rushed off and hacked together some demonstration code without bothering to look any further.  I am pleased to see that the answer I came up with was pretty much the same as Saša’s; I consider him an extremely smart developer and coming up with an answer pretty similar to his  independently makes me feel a bit more confident of my own skills.

The TL;DR version is that you need to construct the functions to be applied in such a way that you can carry forward an indication of either success or failure along with the value to be checked.

defmodule Password do

  defp password_long_enough?({:ok = _atom, p}) do
    if(String.length(p) > 6) do
      {:ok, p}
    else
      {:error,p}
    end
  end

  defp starts_with_letter?({:ok = _atom, p}) do
   if(String.printable?(String.first(p))) do
     {:ok, p}
   else
     {:error,p}
   end      
  end


  def password_valid?(p) do
    {:ok, _} = password_long_enough?({:ok,p}) 
    |> starts_with_letter?
  end

end

And one would use it like so:

iex(7)> Password.password_valid?("ties")
** (FunctionClauseError) no function clause matching in Password.starts_with_letter?/1
    so_test.exs:11: Password.starts_with_letter?({:error, "ties"})
    so_test.exs:21: Password.password_valid?/1
iex(7)> Password.password_valid?("tiesandsixletters")
{:ok, "tiesandsixletters"}
iex(8)> Password.password_valid?("\x{0000}tiesandsixletters")
** (MatchError) no match of right hand side value: {:error, <<0, 116, 105, 101, 115, 97, 110, 100, 115, 105, 120, 108, 101, 116, 116, 101, 114, 115>>}
 so_test.exs:21: Password.password_valid?/1
iex(8)>

A couple of comments on the code.  Someone might ask why password_long_enough?  gets a parameter of a tuple of atom and string. Since it’s the first function in the chain it’s not really needed; all it needs is the string.  I constructed in this way for a few reasons:

  1. It’s more parallel to the other function
  2. The functions are really intended to be rules which should be checked so there should not be an order dependency. That is, they should be interchangeable.

Basically by adding any predicate function that we wish given that it takes a tuple of an atom and a string and the atom is matched against :ok, we can add any arbitrary set of tests we wish to add.

As with most things on this blog, I write this down as much for my own reference as for the edification of others who might read it.  I’m pretty sure at some point in the future, I will need to validate a value through a set of predicate functions and I’ll look at this blog post to see how I can do it.


EDIT: I was reminded of a great blog post written up by Zohaib Rauf on precisely this same idea.  Well worth reading.

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.

Prerequisites For F# and Android Development

If you want to build Android apps with F#, you’ll need the following things:

  • Xamarin Studio (true on both Mac and PC).  I hope soon we’ll have an Android/F# option within Visual Studio but as of today (17 October 2013) it’s not there.
  • F# 3.0 or later (seems to go without saying but just in case)
  • Within XS, you will need both the F# language bindings and the F# For Android Add-ins
  • If you wish to be able to debug the app on your phones
    • On Mac you don’t need to do anything special
    • On Windows you need to make sure you have the proper driver installed from the phone manufacturer.  The Xamarin docs say get the latest Google USB driver but it appears you need to get the specific driver from the phone manufacturer.

By the way, many kudos to Dave Thomas (@7Sharp9) who has tirelessly worked on bettering the Xamarin/Android/F# experience.  None of this would be possible without his hard work.

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.