Phillip Trelford's Array

POKE 36879,255

Code Golf

Last month Grant Crofton popped down from Leeds to the F#unctional Londoners meetup at Skills Matter to run a fun hands on code golf session. The idea of code golf is to implement a specific algorithm in the fewest possible characters. This is not the kind of thing you should be doing in enterprise code, but it is fun, and an interesting way of exploring features in a programming language.

On the night we attempted condensed versions of FizzBuzz and 99 bottles of beer, with Ross and I winning the first challenge and Simon & Adrian the second.

FizzBuzz Score99 Bottles Score

Thanks again to Grant for a really fun session.

F# FizzBuzz

A while back I strived to squeeze an F# implementation of FizzBuzz into a tweet, and with white space removed it weighs in at 104 characters (excluding line breaks):

for n=1 to 100 do 
 printfn"%s"
  (match n%3,n%5 with 0,0->"FizzBuzz"|0,_->"Fizz"|_,0->"Buzz"|_,_->string n)

The implementation, although quite clear, requires a fair number of characters for the pattern matching portion.

After some head scratching we came up with the idea of using a lookup to select the string to display:

N %3 N % 5 Index Output
0 0 0 N
>0 0 1 “Fizz”
0 >0 2 “Buzz”
>0 >0 3 “FizzBuzz”

This took the implementation down to 89 characters (without line breaks):

for i=1 to 100 do
 printfn"%s"["FizzBuzz";"Buzz";"Fizz";string i].[sign(i%5)*2+sign(i%3)]

Another trick is to abuse the sign function, to get 1 if the result of the modulus is above 0 and 0 otherwise.

The lookup trick can be used in other languages, and here’s a few examples, just for fun.

VB.Net FizzBuzz

VB.Net has a reputation for being a little verbose, but using the lookup trick it was possible to it get down to 96 characters (excluding line breaks):

For i=1 To 100:
Console.WriteLine({i,"Fizz","Buzz","FizzBuzz"}(-(i Mod 3=0)-(i Mod 5=0)*2))
:Next

In VB.Net true values translate to –1 and false to 0. This allowed me to simply negate the result of i % N = 0 to compute an index.

Python FizzBuzz

Using a similar trick in Python, where true translates to 1 and 0 to false, I was able to get to a very respectable 79 characters (excluding line breaks):

for x in range(1,101):
 print([x,"Fizz","Buzz","FizzBuzz"][(x%3==0)+2*(x%5==0)])

Python’s simple print function also helped to keep the character count down.

Amanda FizzBuzz

Amanda is a variant of David Turner’s quintessential functional programming language Miranda. Amanda runs on Windows, and is used for teaching FP at some universities.

Using a list comprehension it was possible to squeeze in to a mere 67 characters:

[["FizzBuzz","Buzz","Fizz",itoa x]!(min[1,x%3]+min[1,x%5]*2)|x<-[1..100]]

Note: this is cheating a little as we are not explicitly writing to the console.

APL FizzBuzz

APL is a very mature language, dating back to the 1960s, and is still used commercially today. It also wins hands down in code golf with just 54 characters:

⍪{'FizzBuzz' 'Buzz' 'Fizz'⍵[1+(2×1⌊5|⍵)+1⌊3|⍵]}¨⍳100

APL is particularly strong at matrix processing and provides single character representations for common operations:

Notation Name Meaning
B Index generator Creates a list from 1 to B
¨ Each for each loop
Table Produces a one column matrix
B Floor Greatest integer less than or equal to B

Try APL in your browser now.

Challenge

Can you beat the APL implementation of FizzBuzz?

Have fun!

My First Xamarin Mobile App

Following on from F# week, Xamarin have been running a contest to build your first F# mobile app which ends today. If you missed it you can still enter, run an F# app and get a free F# T-shirt.

Over the weekend I’ve put together a simple calculator app that includes units of measure support:

units calculator


Getting started

I installed the latest version of Xamarin on my Mac. The happy path seems to be the stable release channel these days, as F# is now baked into the IDE. Once it’s installed you can start straight away developing Android apps. For iOS you need to install Xcode from the Apple store too. The iOS emulator seemed to run the faster, taking just a few seconds to build and run, so I settled on that.

The Xamarin IDE includes plenty of project templates for building Android and iOS applications with F#. I used the universal single view application template for iOS as a start point, and the Creating iOS Applications in Code tutorial as a guide. I’d also recommend checking out Rachel Reese’s excellent Introduction to F# with Xamarin article.

Note: F# is a mature, open source, cross-platform language so you get the same compiler in Xamarin as you do in Visual Studio.


Units of measure

F# has built-in support for units of measure so you can write:

let speed = 100<m> / 10<s>

This unit information is used for compile time checking, it has no cost at runtime, and subsequently no meta data is available at runtime.

For the units calculator an expression parser and units implementation is required. This was a case of here’s one I wrote earlier, see:

The implementation uses a couple of F# discriminated unions for defining unit types and a simple recursive decent parser using F# active patterns for parsing expressions. No libraries were imported and the code is just over 200 lines.

You can also play with the units implementation in F# interactive, simply highlight the source in Units.fs and then right-click and execute selected in F# interactive.

Note: Google and Bing both provide unit calculators from their respective search boxes.


Source code

All the source code is available on BitBucket: https://bitbucket.org/ptrelford/units-calculator/src

Loan calculator

Yesterday I came across a handy loan payment calculator in C# by Jonathon Wood via Alvin Ashcraft’s Morning Dew links. The implementation appears to be idiomatic C# using a class, mutable properties and wrapped in a host console application to display the results.

I thought it’d be fun to spend a few moments re-implementing it in F# so it can be executed in F# interactive as a script or a console application.

Rather than use a class, I’ve plumped for a record type that captures all the required fields:

/// Loan record
type Loan = {
   /// The total purchase price of the item being paid for.
   PurchasePrice : decimal
   /// The total down payment towards the item being purchased.
   DownPayment : decimal
   /// The annual interest rate to be charged on the loan
   InterestRate : double
   /// The term of the loan in months. This is the number of months
   /// that payments will be made.
   TermMonths : int
   }

 

And for the calculation simply a function:

/// Calculates montly payment amount
let calculateMonthlyPayment (loan:Loan) =
   let monthsPerYear = 12
   let rate = (loan.InterestRate / double monthsPerYear) / 100.0
   let factor = rate + (rate / (Math.Pow(rate+1.,double loan.TermMonths) 1.))
   let amount = loan.PurchasePrice - loan.DownPayment
   let payment = amount * decimal factor
   Math.Round(payment,2)

 

We can test the function immediately in F# interactive

let loan = {
   PurchasePrice = 50000M
   DownPayment = 0M
   InterestRate = 6.0
   TermMonths = 5 * 12
   }

calculateMonthlyPayment loan

 

Then a test run (which produces the same results as the original code):

let displayLoanInformation (loan:Loan) =
   printfn "Purchase Price: %M" loan.PurchasePrice
   printfn "Down Payment: %M" loan.DownPayment
   printfn "Loan Amount: %M" (loan.PurchasePrice - loan.DownPayment)
   printfn "Annual Interest Rate: %f%%" loan.InterestRate
   printfn "Term: %d months" loan.TermMonths
   printfn "Monthly Payment: %f" (calculateMonthlyPayment loan)
   printfn ""

for i in 0M .. 1000M .. 10000M do
   let loan = { loan with DownPayment = i }
   displayLoanInformation loan

 

Another option is to simply skip the record and use arguments:

/// Calculates montly payment amount
let calculateMonthlyPayment(purchasePrice,downPayment,interestRate,months) =
   let monthsPerYear = 12
   let rate = (interestRate / double monthsPerYear) / 100.0
   let factor = rate + (rate / (Math.Pow(rate + 1.0, double months) - 1.0))
   let amount = purchasePrice - downPayment
   let payment = amount * decimal factor
   Math.Round(payment,2