A Fishful of Dollars

First of all, allow me to apologize for a solid month of failed updates. The world of coaching my son’s football team and bugbashing caused me to want to spend my time at home, asleep, rather than writing about my various misadventures in F#.

To update on the application rewrite, upcoming tax legislation has my firm in quite a tizzy, and is requiring an all-hands on deck approach for the next few weeks. Assuming the bill passes, we may be changing a lot of software, quite quickly, and absolutely none of that has anything to do with an old poorly-written report. The upcoming business need will be drastic, and preparing for that change is important to do.

That said, let’s play around a bit in F#!

I was watching an old episode of Futurama, when a question popped into my mind. If Fry left a bank account with $0.93 in it, at 2.25% interest, would he actually be sitting on a cool $4.3 billion after being frozen for 1000 years? Time to find out!

val fry : float = 4283508450.0

Looks like the math works… but man oh man does it take a while to get there. Using FSharp Charting and iterating over each year…

let fryOverTime = [ 1.0 .. 1000.0 ] 
                    |> List.map (fun t -> compound { Compounding = TimesPerYear 1.0
                                                     Rate = 0.0225
                                                     Principal = 0.93
                                                     TermInYears = t }  )

Chart.Line(fryOverTime
            , Name="Balance over Years"
            , XTitle = "Years"
            , YTitle = "Balance in Dollars")
       .WithXAxis(Min=0.0, Max=1000.0)
// because it's almost impossible to see any change until year 650 or so...
Chart.Line(fryOverTime
            , Name="Balance over Years"
            , XTitle = "Years"
            , YTitle = "Balance in Dollars")
       .WithXAxis(Min=0.0, Max=1000.0)
       .WithYAxis(Log = true)
Fry's Balance
Fry's BalanceIt looks like Fry’s bank account doesn’t get interesting until about 300 years or so. Still, compound interest is a wonder, despite whether or not Albert Einstein said so.

Coming Soon – Application Redesign in F#

We have a reporting application at {Redacted}, one I’ve spent more than a few hours maintaining. A colleague of mine and I (the junior developer I spoke of in a prior post) met up with the business owner of the reporting application, to talk about rebuilding the application in more functional way.

This application is not a terribly complicated one. In short, it takes data from multiple data sources, and re-aggregates it into a series of reports. It has however, had multiple developers come and “peek in”, drop code into it, and leave.  In the current C# implementation, it’s 5 distinct assemblies. There are 8 test assemblies to go with it.  It has a lot of business value riding on it being robust and correct, so the tests do seem warranted.

A word to the wise though… simple things that are more complicated than they should be AND that have a ton of tests are REFACTORING GOLD. Nothing feels better than taking something complex and unwinding it to it’s core essentials, and nothing feels better than doing it in F#!

We took a page out of For Fun and Profit’s DDD page and focused for nearly an hour on the objects and processes involved in this report. Naturally, the process seemed extremely solvable in a functional way.

Unfortunately, due to time constraints on the rest of the day we were only able to start with some very high level type definitions, but those type definitions described our problem in such a way that the business owner was able to see and understand.

We did the whole thing with an instance of VS Code and Ionide, and had types describing the objects and functions involved, all with just a simple “domain” setup in the process. Did we implement anything particularly? Well, kinda yeah, this is perfectly compile-able F# code, which as opposed to Gherkin or some other spec-based “code”, does not need a secondary interpreter.

That’s the crux of this application and function. I think we may be able to get this down to a few pages of code… as opposed to the novella you’d call it now. #FeelingHopeful

Fractions Cont’d, Factoring a Number

As we last spoke about Fractions, we had a simple task after getting a Fraction object. We wanted to reduce them. I was taught to rit educe a fraction by factorizing the numerator and denominator, and then crossing out the common factors. Then, multiplying the numbers together to get the reduced value. E.G.

 60        2 * 2 * 3 * 5        2 * 2 * 3 * 5       2 
----  =  -----------------  =  ---------------  =  ---
 90        2 * 3 * 3 * 5        2 * 3 * 3 * 5       3

The example above is a simple one.

So the question is, how do we best factor a number?

First, we define the mechanisms we require.  We need a way to define that a number is a factor of another.

let isFactor i pf =
    i % pf = 0I

What does this method buy us? First, it gives us a simple True/False flag defining whether or not a number is a factor of another. Namely, if the module of i and pf is 0I  (specifically, zero, as a System.Numerics.BigInteger), then we know that pf is a factor of i.

Next, we define a recursive function that takes two parameters, start and i. The idea of this function is to return a sequence of numbers from start to i, counting by twos. The start value is an option type, so if not present, it assumes 2 is a valid option, and starts the sequence there, then goes with every odd number. Note: I’m accepting as a given that this will do some checks against numbers it’s unnecessary to do that against.

Finally, I define my internal recursive loop to accumulate the resulting found factors. An interesting thing we’ve got here is some issues of partial application for function calls. The “findFunc” function is a partially applied isFactor call, with the i value already passed in. The reason I did this was to make the Seq.tryFind call easy to use, because the Seq.tryFind call is shaped like this:

('a -> bool) -> seq 'a -> Option 'a

But to get to my “bool”, I needed more than just a single ‘a parameter.  That’s why partial application was so valuable here! Instead of changing the function signature to meet my needs, I simply made a quick, easy to reference function by supplying some arguments ahead of time.

The rest of the function is fairly apparent. The loop recurses over the sequence, finding factors and then appending them to as the head of the accumulator (f::acc), until the Seq.tryFind call eventually returns None, and the accumulated list of factors is returned.

The last bits of the function just wrap up return values. In this case, we check for negative numbers, or a 0I being passed in.  Negative numbers are fairly easy to factor as they only require normal factorization of the inverse with -1I appended, and 0I simply returns an empty list.

With that, we get our results (mapped to ints, for ease of readability.)

getFactors 64000I |> List.map int;;
val it : int list = [5; 5; 5; 2; 2; 2; 2; 2; 2; 2; 2; 2]

getFactors 6423453000I |> List.map int;;
val it : int list = [8599; 83; 5; 5; 5; 3; 3; 2; 2; 2]

getFactors 9536923853063I |> List.map int64;;
val it : int64 list = [354041L; 178393L; 151L]

getFactors 953692385306332I |> List.map int64;;
// this one's still chugging.

The last thing to do here is to figure out how to avoid unnecessary iterations but that’s a topic for another blog.

Fun Friday (Monday version) – Fractions

This will be a slightly longer series of posts. I thought about treating fractions as a distinct problem, and wanted to find a way to code reducing fractions in a logical and meaningful way.

The first problem was describing the type. Naturally, you can do it a as simple pair:

type Fraction = int * int
let a = (-1, -2 : Fraction)  // negatives?

But that design describes some issues I’m not super keen on handling, namely negative denominators. Mathematically, negative denominators aren’t all that complicated to deal with, but in my head, it seemed unnecessary to solve them, so that led to the following:

type Fraction = int * uint32
let a = (-1, 2u : Fraction) // ugh, not as clean as I'd like

Now we’ve dealt with the negative denominator problem, but that leaves us describing fractions in a sort of “planar” way. Great for talking to a professor, but I’ve always been something of a “make it clear” personality. Record types work well for this.

type Fraction = { Numerator : int; Denominator : uint32 }
{ Numerator = 1 ; Denominator = 2u; }

Nice and pretty. Except 0 is a valid uint32 value. Shit.

type BiggerThanZero = private BiggerThanZero of uint32

module BiggerThanZero =

     let create uintValue =
          if (uintValue > 0u ) then BiggerThanZero uintValue
          else failwith "No zeros"

     let value (BiggerThanZero u) =
          u

type Fraction = { Numerator: int; Denominator: BiggerThanZero }

Alright. Something is breaking my “F# is less verbose” than other languages spidey-sense here, in C#.

using System;

public class Fraction
{
    public struct BiggerThanZero
    {
        public BiggerThanZero(UInt32 u)
        {
            if(u == 0u) then 
                throw new ArgumentException("No zeros");
            Value = u;
        }

        public UInt32 Value 
        {
            get;
        }
    }

    public Fraction(int numerator, BiggerThanZero denominator)
    {
        Numerator = numerator;
        Denominator = denominator;
    }
    public int Numerator { get; }
    public BiggerThanZero Denominator { get; }
}

Nope, spidey-sense was off. C# is still more code. Phew… thought I was going to have to go back to OO land. 🙂

OK… so now we have a domain object. We cannot represent an object in the domain that is “invalid” in any way, so fundamentally, our functions should be easy to reason about.

So first thing… decimals to my new “Fraction” type.

let getFraction decimalValue = 
    let rec fract dm =
        let a = (d * m)
        let r = a % 1.0m
        match r with
            | 0.0m -> { Numerator = (int a) ; Denominator = BiggerThanZero.create (uint32 m)}
            | _ -> fract d (m * 10.0m)
    fract decimalValue 10.0m

This function goes back to our old friend, the recursive inner function. We take our input decimal value, and multiplying it by 10, and calling the result ‘a’ (shorthand for ‘amount’). Then we take ‘a’, and get the decimal part of that value by applying the modulo function to it and 1.0, and naming that value ‘r’ (shorthand for remainder). Assuming that ‘r’ is non-zero, we recurse into the loop, updating the multiplier to another factor of 10 greater than what we had before. Otherwise, we simply return a Fraction object, with the Numerator set to ‘a’, and the Denominator set to the multiple. E.G.

 

getFraction 0.4m;;
val it : Fraction = { Numerator = 4; Denominator = BiggerThanZero 10u }

getFraction 0.542m;;
val it : Fraction = { Numerator = 542; Denominator = BiggerThanZero 1000u }
 
getFraction 0.8675421m;;
val it : Fraction = { Numerator = 8675421; Denominator = BiggerThanZero 10000000u }

This is the start of our Fractions work, and although it’s correct, it’s certainly got some potential error cases. Our int and uint32 bases for values could be overflowed. That’s fixed in the following.

Next time, we’ll deal with reducing our fractions.

 

Managing Expectations

Non-F# content warning: Skip to the next one if you’re not interested in general stuff.

Generally, a working programmer doesn’t have too many difficult “non-programming” tasks. Difficulty is the name of our game, and we like it that way. That said, one of the most critical skills a developer has is to manage folks’ expectations of you. Thought-work, in general requires a level of communication that seems nonstandard and maybe a little unnatural to your work.

The reality of being a working programmer is this: Your boss probably doesn’t exactly understand what you’re doing. Your boss may be relying on you to do a good job, regardless of his/her detailed understanding of your work. Making sure those expectations are set properly is key to keeping this relationship copacetic.

An Example: A customer asks you to sneak in a quick feature. You’ve taken a swag at it, and it looks like it won’t take more than a few hours and doesn’t impact anything, so you agree. Your customer leaves you happy, and everything seems fine. Fast forward to a week from now. The feature you were supposed to be working is late, and blocking everything going out. Your customer, who felt like his request was tiny, and shouldn’t impact anything, complains to your boss that the feature is late. Your boss, who has no idea that you agreed to anything, has now the unpleasant task of defending why the feature is late, even though she/he didn’t know it was part of the release. That makes her/him look disorganized and incompetent, and that’s not how you want to make your boss feel or look, even if you hate her/him.

Take a look at your day to day interactions and communications. Do folks know what you are doing? Do they know when you releasing your work?

Here’s a tip. Don’t assume that folks are reading every email, or “making the connection.” Make yourself very clear about what you are doing, when you expect to be complete, and if there are any items blocking you. If you are not sure yourself what to be doing, there is a very good chance you have not managed expectations well.

 

 

Fun Friday – Diamonds are Forever

Sometimes you write code you’re just not super happy with.

The Diamond Kata is a simple kata to take a single character parameter, and return a “diamond” shaped string.  Examples:

diamond 'A';; 
val it : string = "A"

diamond 'B';;
val it : string = "
 A 
B B
 A "

diamond 'C';;
val it : string = "
  A  
 B B 
C   C
 B B 
  A  "

etc;;

That’s how I describe this Kata I was working on. I’m just not super happy with it. It feels wordy, and a bit inelegant. Still, it does work (as long as you pass a character ‘greater’ than upper case A. I should probably enforce that sometime… but for now, here it is.

TDD in Fable and React – can it be done?

I’ve been working to evangelize F# through {Redacted} for about a year now. I started with tests, and the build server, using FAKE and using standard tools.

In one of our Dev org meetings today, a junior developer brought up his experience with Fable, after noting how much fun I was having and sharing while coding in F#.

His review was fantastic. He was using React, and comparing native Javascript versions to what F# was enabling him to produce, and the code was more terse and wonderful. One of the things you immediately notice about React components is that the markup is still quite messy, and there is certainly something “icky” feeling about combining your markup and javascript. With Fable, Elmish and React, you are simply calling functions, with no extra tags that you don’t need.

Fundamentally though, the debugging story wasn’t great, and the TDD story was equally difficult, as he couldn’t figure out how to immediately test against a virtual DOM in his Fable F# code. For now, I ask the community, how do you best do that? How do you test that the virtual DOM actually contains the react component in question? How do you test it? I have a feeling that in the next week or so, I’ll find out.

Modeling the Domain : Short Codes

Anyone who’s read For Fun and Profit’s domain modeling exercise may see some similarities in today’s code. Mainly, I wanted to point out the value of quickly being able to create types that describe my functions here.  For context, I’m in the middle of rewriting a sticky report that consumes data from a ton of different places… this is an example (slightly modified, to avoid spilling too many of {Redacted}’s beans.)

In the above, we’re dealing with a thing called ‘Short Codes.’ At redacted, we have a shortened string which represents many of our more common domain objects, called a ‘Short Code’ which makes domain objects easily identifiable when viewed in spreadsheets.

In C# code, we’ll typically treat these objects as simple strings, or you deal with of domain types as espoused in Vladir Khorikov’s Pluralsight course, “Applying Functional Principles in C#”.

But in F#, you get drastically simpler code, that gives you similar benefits.

  1. Any change to ShortCodes can be done once, and all references using it get the change. That’s as DRY as it comes.
  2. ShortCodes can be equal to each other, but AccountShortCodes cannot be equal to ProductShortCodes cannot be (try it in FSI, you get compiler errors!)
  3. The modules allow us to retain the business logic, so we avoid the annoying issues of duplicating validation code everywhere. If I reference an AccountShortCode, it’s implied that I created one successfully in the first place!

The code to do stuff becomes quite easy:

type ConsumingRecord = { ShortCode : AccountShortCode
                         ImportantValue : decimal }

let m = AccountShortCode.create "APPLE";;
// m is an AccountShortCode option, because of the 
// validation logic there, so we need it from the option, 
// before we push it into our consuming type.

let n = { ShortCode = (Option.get m)
          ImportantValue = 5.0m}

The subtle thing here is that we have to actually deal with the fact that it’s an option. We CAN fail to get an AccountShortCode here, depending on what we pass in, but once we have a “ConsumingRecord” object, the validity of the ShortCode is guaranteed. This only works, however, because F# doesn’t do nulls. Once your language does nulls, it throws this stuff right out the window.

But I’m sure eventually C# will get that, too. You’ll just have to use an attribute to make your class less C-sharpy. 😉

Not Much F# Today

You ever have one of those days when everything goes wrong and it’s all a C# developer’s fault? I kid, of course, but it made for a difficult day with almost no sitting at my own desk to actually get anything done.

My mission is to update this blog every day, regardless of what I actually accomplish for the day. Today, I saved the world, and solved problems that were a little more tactical in nature. I did enjoy a welcome to the firm lunch with a new QA in the office, but beyond that, very little coding.

Fun Friday – Roman Numeral Kata

Roman numerals are about the most useless things on the planet nowadays, provided you aren’t rolling credits at a movie screen.

However, if the Romans DO return, we have a solution to the pesky number problem. I present you my F# implementation.

I endeavor to explain for those not yet converted to the F# happy-path.

The first lines (1-3), declares a value (“vals”) as a list of tuples. Those tuples consist of a number, and it’s equivalent textual value in the Roman Numeral form. The ordering is important, as it goes from largest numerical value to smallest in the list.

Both functions defined here (toRoman and fromRoman) are very similarly designed. They start with a single parameter, and then define and internal looping function that actually creates the resulting value. Then they call that internal function with an “empty” accumulator, the initial parameter value, and the vals list declared above. If you run a simple test in FSI with these functions you should easily get some good results:

> toRoman 54;;
val it : string = "LIV"

> toRoman 2017;;
val it : string = "MMXVII"

> fromRoman "MMXVII";;
val it : int = 2017

Internal loops with an accumulator are common in functional code. Our loops use the “acc” (aka, accumulator) parameter to sum up the matching numbers in the fromRoman function, and to build the resulting string in the toRoman function. The internal loop  matches the incoming list, and compares it against 3 possible options. The first possible match is against an empty list. If the list passed in to the loop function is empty, it simply returns the acc value. The second match is a list with the head of the element deconstructed as a tuple (i, s), filtering when the “n” parameter (of the loop function) is larger than (or equal to) the “i” value in the tuple. In that case, we simply call the loop function again, appending the s value to the acc parameter, subtracting the i value from the n parameter, and passing the same list into the function again. Finally the third option is when it’s just a simple list object that has a head and a tail (the match order counts) and it passes the existing acc and n parameter values to the loop function with the tail of the list.

When I pass in 54 into the toRoman function, the first thing that happens in that function is:

1) The loop function is defined and then called, with “” as the acc parameter, 54 as the n parameter and the vals list [(1000, “M”)…(1, “I”)] as the list parameter.

2) The loop executes, matching against the list parameter.

3) The list is not empty, so it skips the first match.

4) The first value in the list (1000, “M”) is capable of being represented as a tuple (i, s), and the list itself matches the cons operator (“::“) as well, but the “when” setting n >= i does NOT match, because the n parameter is 54 and the i is 1000, so it skips the second match.

* Reread and, make sure you understand this part, as it’s the critical point of the function.

5) The final option matches, and calls loop again, this time with parameters: acc = “”; n = 54, and list = [(900, “CM”)…(1, “I”)] 

6) The steps 3-5 execute again. The head of the list is compared, until eventually the “n” parameter is larger or equal to the corresponding “i” (from step 4).
(900, “CM”) -> Nope
(500, “D”) -> Nada
(400, “CD”) -> No Dice


(50, “L”) -> That’s a match!

7) Since that match occurred, we STILL loop through the execution, but now we modify our parameters a bit. Instead of the plain old acc, now we apply a function to the acc to accumulate the value; acc is no longer “”, it is now “” + “L”.  The variable n is modified as well. It is no longer 54, it becomes (54 – 50). The list value stays the same [(50,”L”)…(1, “I”)].

8) The new values are now matched, and the process continues. The list is still not empty, and the new n value (4) is clearly less than 50 (the first element in the list), so we move on through the list, in the same way we did before but against the new n value (4):
(50, “L”) -> Nope
(40, “XL”) -> Negative
(10, “X”) -> No Dice
(9, “IX”) -> Sorry
(5, “V”) -> Not quite
(4, “IV”) -> Yep!

9) The result updates acc to “LIV”, and n to 0. We loop through the remaining 2 items in the list (4, “IV”) and (1, “I”) and get to the last possible match [], the empty list.  The last match returns the acc passed in (“LIV”). That becomes our final value, and is the result of our toRoman function.

The differences between fromRoman and toRoman are simply related to the data types involved. String “subtraction” doesn’t work with a simple minus sign (at least, not without defining a new infix operator), so instead it’s “str.Substring(s.Length).” String comparison doesn’t work with the >= operator, so str.StartsWith(s) was recruited to do the job. Everything else largely works the same, the accumulator accumulates the values while the function executes and the str variable is “decremented”, until the list is exhausted.

There are some clear flaws in my implementations here, and I accept them for what they are. Firstly, in the toRoman function, negative value parameters all return an empty string. I don’t remember my mathematics history there, and I am not sure if they even actually had the concept of negative numbers back then. If you are a history buff, and know the answer, please comment and let me know. Secondly, the fromRoman function isn’t validating the incoming text. You could submit something things like “CDCDCD”, and it would return 1200, even though the input is clearly wrong. Finally, when you put in an exceptionally large number into toRoman, you can end up with a LOT of “M”s, simply because the vals list doesn’t contain enough “domain knowledge” about larger numbers.

Still, it largely works, so for a Fun Friday, I’m happy with it. Enjoy!