Tag Archives: fsharp

Setting up quick API with F# and Azure Functions

As mentioned in my last week Elixir blog post, I produced some quick fake API based on Azure Functions. I thought it’s gonna take a couple of minutes, but it turned out to be a whole adventure in itself.

The creating of a function is a breeze.

  1. Go to Portal, click big green “+” sign and search for “Function App”Screen Shot 2017-04-17 at 16.34.00.png
  2. Pick Function App published by Microsoft
  3. Fill all the necessary fields like App name (must be globally unique) or location. For hosting plan I used “Consumption plan” which means, I pay only for the time that function is running. I also like to pin my stuff to the dashboard, so it’s easier to find.Screen Shot 2017-04-17 at 16.37.38.png
  4. It will take several minutes to deploy.
  5. Now you can create your functions for the app. F# is hidden in small print just above “Create this function” button. So click “create your own custom function”.Screen Shot 2017-04-17 at 16.40.40.png
  6. Then with Language drop-down, pick “F#” and for Scenario – “API  & Webhooks”. There should be on the F# function triggered by HTTP request. That’s the one you want for API.
  7. You’ll get premade piece of code with a simple function that is triggered by HTTP POST with name object and responses “Hello “.

Then I started writing the logic I wanted. I made an array of hard coded airport data. I made the function to accept only GET requests (you can change it in function.json file). In code, I parse query strings and get the airport IATA code. If I have this airport in my array, I response 200 with JSON containing the data. Otherwise, I return 404. If there’s no parameter in the query string, function answers with 500.

It’s relatively simple and straightforward F# code. I just struggled a lot with debugging. The small editor on Azure doesn’t give you static analysis, nor type information and no squigglies. You need to run the function and check for compilation errors or runtime errors. There was also some weird scoping behaviour, that forced me to declare the Airports array within the function. Anyways, after 2hrs I had an API that did what I wanted. You can see the code below. It’s not bulletproof, but it does the job. And I got to play with Azure Functions a bit.

If you want to read more about other types of F# Azure Functions, Mathias Brandewinder wrote recently two posts about timer and queue triggered functions.

That’s all for today. Tune in next week for another part. Also, check previous episodesAnd if you’re interested in machine learning, look into my weekly link drop.

Advertisements

Elixir vs F# – opinionated syntax comparison

Note: There are some awesome comments to this post that add a lot of value. Please check them below.

This is the second part of my Elixir adventures and another post for “Get Noticed” competition.

I was planning to start furiously coding on my project for this second post and start building some web API with Phoenix. But Gutek suggested, that first I should really dig into some internals that will help me understand how Phoenix works – thanks for this advice. On top of that, I didn’t really have time to dig properly, but I managed to look a bit into syntax and I have mixed feelings.

I won’t be doing an introduction to Elixir post here. You can find a lot of resources on that, for example, Gutek’s series in Polish, official documentation or this short article. Instead, I’m gonna compare it to something that I’m familiar with –  F# syntax. And it’s nowhere near comprehensive comparison. Just a few things that I found interesting and worth noting.

Comparing stuff

Right from the start, there are few differences here. F# uses just ‘=’
to compare if two things are equal. Elixir has two comparison operators ‘==’ and ‘===’. First one is standard compare operator. Second, from my current understanding, is useful mostly for comparing if numbers are of the same type. To explain, look at this example:

// F#
1 = 2             // false
1 = 1             // true

1 = 1.0           // This yields compile error
float(1) = 1.0    // true

Although we didn’t declare any types in F#, it will infer them during compilation. And as a strongly typed language, will not allow comparing values of two different types.

# Elixir
1 == 2            # false
1 == 1            # true

1 == 1.0          # true
1 === 1.0         # false

Elixir is dynamically typed. It means, that it will also infer types, but this will happen in the runtime and also will do casts for you.

For not-equal F# uses ‘<>’ and Elixir ‘!=’ and ‘!==’. Generally, Elixir is here more consistent with most programming languages, so I’ll give it a point here, but I appreciate type safety of F# also. You can also notice that those languages use a different convention for comments.

In Elixir ‘=’ is also used for matching which is quite powerful.

Immutability

Although both languages are immutable by default, there are some differences in approach.

In Elixir, value is immutable so you cannot change it, but you can assign the “label” to some other value.

# Elixir
a = 1             # value "1" is now labelled "a"
a = a+1           # label "a" is changed: now "2" is labelled "a"
a = a*5           # value "10" is now labelled "a"

But if you want to refer to the current value of, i.e. when using match operator, you can do it this way:

# Elixir
b = 1
b = 2             # rebinding variable to 2
^b = 3            # matching: 2 = 3 -> error

First thing that came to my mind when saw it, were C language pointers 🙂

F# allows mutability, but it has to be openly declared, and then you need a different operator to change the value. Mutability is mostly allowed for compatibility reasons with .NET libraries, so you shouldn’t abuse it.

// F#
let a = 1         // binding value "1"" to label "a"
a = 2             // returns false (it is just comparing)
a <- 2            // compile error

let mutable b = 1 // binding value "1"" to mutable variable "b""
b <- 2            // changing value of variable "b""
b = 2             // returns true

In this part, F# is for me clear winner. You cannot change value bind to a label. It is much less confusing and makes more readable code.

List operations

List operations are generally very similar. What I found interesting in Elixir, you can match not only head and tail, like in F# but several first elements:
EDIT: As anonguy pointed out in the comments, that’s also possible in F#. Updated the code sample.

# Elixir
[ a, b, c | tail ]
// F#
head::tail
a::b::c::tail // that also works

There are two things worth mentioning while we’re on lists. Pipe operator (|>) works pretty much the same in both languages. In Elixir it binds the first parameter of the function, and in F# last one, but that’s the main difference. It’s a matter of convention and doesn’t really matter in the end. Just worth knowing.
EDIT: as Chris and Paul Blair pointed out, this has a tremendous impact on how currying and partial application works and makes F# much easier in that regard. Check out the comments for details.

The classic approach to lists is that you usually iterate through them with for loop. It’s possible in F#, but Elixir doesn’t have “for” loop. You have to do it in a more functional way, i.e. through recursion. For me, that’s a huge plus on Elixir side, because it forces you to use proper functional approach. In F# for loops are a gateway drug to imperative programming :).

Functions and modules

The first thing that I find annoying in Elixir is that every ‘def’ and ‘defp’ must be paired with ‘end’. It’s like curly braces all over again. Or Visual Basic. It makes code dirty and is excessive. In F#, blocks of code are delimited by the level of whitespace, similar to Python.

In Elixir, functions must be wrapped in Modules. It doesn’t create a big pain, but again – something I don’t have to do in F#. On the other hand, Elixir allows you to do multilevel Modules, which may be convenient in some situations.
EDIT: Anil Mujagic mentioned in the comments, that it also works in F#.

Pattern matching

A bit about Elixir pattern matching was mentioned in the first paragraph. “=” parameter has some impressive qualities. You can also pattern match on function parameters, like shown below in the second example. And you can further simplify it with guards.

# Elixir
# case statement
def blank?(value) do
    case value do
        nil    -> true
        false  -> true
        ""     -> true
        _other -> false
    end
end

# pattern matching on function parameters
def blank?(nil),    do: true
def blank?(false),  do: true
def blank?(""),     do: true
def blank?(_other), do: false

# pattern matching on function parameters with guards
def blank?(value) when value in [nil, false, ""], do: true
def blank?(_other), do: false

In F# it looks similar to the case statement in Elixir. You can also use guards with it and much more.

// F#
let x = 
    match 1 with 
    | 1 -> "a"
    | 2 -> "b"  
    | _ -> "z" 

I couldn’t recreate the same example easily, because of strong typing of F#.  The Same variable cannot have values of different types, and nulls are non-existent in this language. You could have something similar using discriminated unions.

I’m not a fan of Elixir’s approach to this problem with declaring several functions. I prefer F# way again.

Summary

As mentioned in the beginning, I have mixed feelings. For the last couple of years, I’ve been hearing a lot how beautiful Elixir is. And I can imagine for a lot of folks coming from other languages it is. But I’ve been spoiled with F# for last 5 years and I must admit, it’s still my number one. That being said, Elixir lands on the strong second position in terms of beauty. I do appreciate some big uncompromising design decisions that José made to make Elixir much more functional. F# has some “gateway drugs” to imperative programming, as they wanted to leave that option open too and be compatible with the rest of .NET. Big points for Elixir for that. There are some features of F# like discriminated unions or units of measures, that I haven’t found a good replacement in Elixir, but I’m also at the beginning of my journey. I also like F# more for strong typing.

Additional resources

F# has an abundance of operators. Some of them are really crazy. Check this Microsoft document to see all of them.

Quick guides on Elixir and F# syntax. The second one comes from the excellent blog of Scott Wlaschin. If you want to dive into F# more, I highly recommend it.

Next week I’ll be diving into internals. Hopefully, I will find time for that. Come back next week for more Elixir, and if you’re interested in Machine Learning, check my subjective drop of interesting articles in that area.

This post was edited to fix inaccuracies that were pointed out in the comments. Thank you for kind, constructive and informative comments!

DevSum 2015

I’m right now on in Arlanda airport, coming back from DevSum 2015. It was my first DevSum, and it was awesome.
Conference had two days and four tracks. Everything conveniently located in central Stockholm at hotel Clarion Sign. Very close to central station and places for evening activities. The atmosphere was very friendly. I met well known faces from speaker community and made some new friendships. It was most social conference I attended this year, very much similar to how DevDay feels. Most of the speakers didn’t sit in the close “speaker’s lounge”, but mingled with attendees, all led by Tibi, the King of DevSum :).
I didn’t attend many talks, but there were few very intersting. Among them Mark Rendle’s C# 6 talk, Troy Hunt’s and Niall Merrigan’s security talks and Hadi’s “silver bullet” talk. There was also Rob Ashton rant about how Erlang is awesome, but I’m not sure he convinced anybody showing mostly his console scrolling with loads of code and hard to understand error messages flying around. But it was hillarious so that’s ok.
My talk went fairly well. It was another installment of the talk I did at Swettugg and LambdaDays. I had around 30 people on public and I hope they got interested by type providers. Big thanks to Tibi and Cornerstone for this opportunity. Slides and code are on github.

Month of spreading F# love in Poland

In last month or so I did three talks on F# in Poland. I can see gaining interests and there’re already other people speaking about F# in Polish community. This is awesome!

Kraków, 25th September

A Day before DevDay KGD.NET organized meetup with two talks. This was great opportunity for my employer tretton37 to get some more street cred in Poland, so we decided to sponsor some food and drinks. There were two speakers – me and Maciej Aniserowicz, who’s kind of a rock star of Polish .NET community (BTW, check out his new podcast (in Polish)). I did my already well known introduction talk to F#. I had quite a big audience (around 100 people) and they were very engaged. I enjoyed great question and feedback I got after the talk. Looks like it’s very active .NET group. I used the same slides and code as in Warsaw couple months before.

Next dey was a DevDay :). I’m big fan of this conference and it delivered again. There were a lot of semi-negative opinions on the Internet afterwards, which is very sad and unfair. Looks like DevDay became victim of its own success. Last year was fuckin awesome, and people had some overgrown expectations. The truth is, it was fuckin awesome again this time and I can’t wait for next year’s edition. Videos are already online and you can watch them on youtube. But the strongest point of DevDay for me is community impact. It made largely distributed Polish .NET scene more united. People are visiting each other’s group and exchange experiences and knowledge. Programmers from all around Poland know each other better and lot’s of credit for that goes to Michał and Rafał.

Interwebz, 18th October

On Saturday evening I did a talk on Polish virtual conference dotnetconf.pl. From statistics I could see there were about 70 people watching it live. It’s a little bit weird to talk to computer without seeing your audience. I’m not happy how this talk went, but you can judge by yourself, because it’s been recorded (Polish). Feedback I got afterwards kind of matched my expectations – 24 positive, 16 neutral and 2 negative opinions. Again – same slides and code as in Warsaw.

This was the second edition of dotnetconfpl, great initiative by Michał, Paweł and Jakub. It’s Saturday afternoon full of code. Made by Polish developers for Polish developers. And because it was virtual, I could do talk from my desk in Sweden. I also very enjoyed discussions that went on whole day on dedicated jabbr channel.

Poznan, 30th October, PolyConf

Few days ago I did completely new talk. This time about cross-platform mobile development with F# and Xamarin. So this was new talk, and also my first talk in English, and biggest audience so far. Lot’s of new experiences. I was quite nervous before, but seems like everything went well. I’ll see video in a couple of days to make sure, but right now I feel it was my best talk so far.

The conference itself is evolution of well known RuPY. This time they widen topics to other programmic languages, so you could witness talks on JavaScript, Haskell, Erlang or F#. Pretty cool experience, and lot’s of inspiration how to move concept from other technologies to my daily job. The conference, even though it was hosted in Poland, gathered mostly international crowd. I’m putting it on my calendar for next year, because really enjoyed it.

What’s really cool and makes me happy, there’re other people who start talking about F# in Polish community. Few weeks ago my friend Kuba Walinski asked me if he can reference my talk, as he’s gonna do his own about F#. Hell yeah, you can. It’s great that we’re spreading F# love :). He spoke at Developer Days in Wrocław and you can read his thoughts about it on his blog.

There’re some other F# events coming up in Poland, so I’m thinking about starting some kind of Polish Monthly F# news, similar to Sergey’s weekly news, but focusing on our local community. Stay tuned :).

Talking F# in Warsaw

Two weeks ago I had another opportunity to practice my public speaking skills. It took me some time to write this post, because in the meantime I spent few days in Krakow. And Krakow is a different state of mind.

This was another instance of my introductory talk to F#. It went a little better than one on get.net, but still I think there’re things to improve. I got really good feedback from Gutek, who came to see this talk. There were also some other friends from Warsaw – some of them I haven’t seen for years. It was a pleasent surprise.

Warsaw .NET usergroup seems to be similar size to one in Gdansk. There were about 40 people attending. Interesingly, some of them came there for the first time, just because of the topic. Good news that F# is getting some interest in Poland. I got best ever set of question after this session. You could clearly see people are interested and want to know more. Really liked that!

What I didn’t like is that there were no networking activities afterwards. Fortunatelly, there were some friends mentioned before, so we went for some food and drinks. Overally good time, and I’m happy I managed to get there on my way to Kraków.

On the bonus note, I had with me ticket for leetspeak to raffle. Leetspeak is tretton37‘s conference, that we organize every autumn. This year it’s happening on 4th October in Gothenburg. Tickets will be available soon.

WP_20140710_19_41_22_Pro

As usually, slides and demos landed on Github.

There are also good news. I’m doing new F# talk, focused more on cross-platform capabilities. Looks like I will present it on PolyConf and WarmCroc in next few months. I’m excited and terrified at the same time, because they’re gonna be my biggest speaking gigs.

Speaking – “WTF# and why should you care” at get.net conference in Łódź

Nearly two weeks ago I had my first opportunity to speak at a conference. Get.net was organized by Łódź branch of Sii and featured all kinds of talk about .net technologies. Among the speakers you could find many familiar and well known faces from Polish dev scene like Maciej Aniserowicz, Jakub Gutkowski, Basia Fusińska, Michał Śliwoń or Rafał Legiędź. I was humbled and honored to speak in such company.

Speaking at conference isn’t much different than speaking at user group. There were just more people and I had to use microphone. Unfortunately it was the kind of mike you have to hold in your hands and this made live coding quite a challenge. Many other speakers had that issue and I hope organizers will know better next time. Apart from that, conference was quite well organized. Also venue was really nice.

My talk was slightly modified version of one I did for tricity .net group last month. But this didn’t make me feel more confident about it. After all it went quite well and there were even some positive tweets. This is good, right? I hope this sparked some interest for F# in Polish .net community. Overall this was nice experience, and I will actively look for other chances to speak at conferences.

Slides and code are on my github.

BTW, I’m writing this post during Craft Conference in Budapest. I’ll do some writeup next week.

Speaking – “WTF# and why should you care” at Tricity .NET Group meetup

Last week during local .net group meetup I did my first technical talk ever. Well, I did present some stuff on internal meetings in company before, but never for so many people, whom I don’t know.

I was quite nervous before – for many reasons. First of all, I’m not some F# guru. I don’t feel fully entitled to share knowledge about it. I also don’t feel very confident in public speaking situations. But it all come around nicely. I’m generally satisfied how it went.

I’m presenting it again in one month at get.net conference in Łódź, Poland. Based on this experience, I will change few things in this talk. But in general, this was good training.

If you have doubts “should I present something at usergroup”, JUST GO DO IT. But before read Zach Holman’s hints on speaking.io. I found them very useful.

Slides from this presentation are on my github. Code examples I used, were mostly from tryfsharp.org.