Archive

Archive for March, 2013

F# Koans – Stock Example

March 31, 2013 10 comments

At Leeds Sharp the other day, we started doing the F# Koans as a way of of trying out the language, with the aim of expanding our minds with some functional programming.  A bit like coder’s LSD, if you will.

The koans are pretty good at introducing you to things, although initially it’s a bit too easy to get through them without really understanding what’s going on.

However, when you get to the stock example that all changes, as you have to actually use some of what you’ve learned to solve a more involved problem. The purpose of this post is to put up my solution  in the hope of getting into a bit of a discussion with others who’ve done it, at Leeds Sharp or otherwise. I have no doubt that my implementation could be improved, so any advice would be more than welcome!

module ``about the stock example`` =

  let stockData =
    [ "Date,Open,High,Low,Close,Volume,Adj Close";
      "2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26";
      // ...
      "2012-02-29,31.89,32.00,31.61,31.74,59323600,31.74"; ]

  // function to split a comma-separated string into an array
  let splitOnCommas (dataAsString:string) =
    dataAsString.Split([|','|])

  // function to take the desired parts of the array as a tuple,
  // including opening-closing difference
  let createPriceDifferenceTuple (fullList:string[]) =
    ( fullList.[0],
      abs (Double.Parse(fullList.[1]) - Double.Parse(fullList.[4])) )

  let maximumDifferenceTuple =
    // split strings into arrays, ignoring header
    List.map splitOnCommas stockData.Tail
    // map arrays to tuples
    |> List.map createPriceDifferenceTuple
    // get maximum tuple based on second element (price difference)
    |> List.maxBy snd

  [<Koan>]
  let YouGotTheAnswerCorrect() =
    let result = fst maximumDifferenceTuple // get date, first item in tuple
    AssertEquality "2012-03-13" result

Categories: Development, F#