Blog

Go Back
  • The Sieve of Eratosthenes and F#

    There is a problem on the Euler project, www.projecteuler.net, which asks to find the sum of all values under a given number. Problems on the Euler project have a range of solutions, where at least one solution has a runtime of under 1 minute. A popular, time efficient algorithm that finds all primes in a given range is the Sieve of Eratosthenes. The basic algorithm is: Create an array that contains all values from 2 up to the final maximum value Starting at 2, For each value in the array, mark all items that have indices of the current value that are multiples and NOT equivalent to the current index as 0 (eg. index mod [current value] == 0). March forward until you hit a non-zero value in the array, then mark all multiples as 0. Halt condition: stop when you cross the midpoint of the ...

    Comments0

    Full story

  • Greatest Prime Factor in F#

    Today I was reading an article in The Onion, Conquerors You May Have Missed,  and noticed that the number for the ant looked like it might be a big old prime, or at least have a large prime divisor. (For reference, the ant is # 43,168,974,563,247.) There are a number of algorithms for finding this answer, but my favorite is a little brute force algorithm that keeps dividing the big number by some other value until the two numbers are equal. Yes, I know I can short circuit a bunch of testing via a square root function, but BigInteger doesn’t have a sqrt function (yet…). Anyhow, I cobbled this together and it worked right out of the gate: let rec largestFactor x y = if (x = y) then y else let z = x % y if z = 0I then largestFactor (x/y) y else largestFactor x ...

    Comments0

    Full story

  • New F#/WCF Article up at InformIT

    My article on programming REST services with F# and WCF went up at InformIT. Please go read it! http://www.informit.com/articles/article.aspx?p=1394625

    Comments0

    Full story

  • Solution for Daily WTF Praxis on 8-5-2009

    Over at The Daily WTF, they’ve started posting programming puzzles. The latest one is a puzzle where a set of locker doors are toggled, starting from the closed state, to the open state. Starting at a step size of 1 and stopping at a step size equal to the number of lockers, one toggles each door. At a step size of 1, all doors are opened, step size of 2, all the even doors are closed. At a step size of 3, door 3 is closed, door 6 opened, and so on. Many of the solutions observe that only perfect squares remain opened when the algorithm is complete. That option is easy, but I wanted to do one that mimics the jocks effort of brute force solving the problem.   // Init the lockers to the initial state // and mark all doors as closed (false) let sw = ...

    Comments0

    Full story

  • Source for Amazon Web Services Application

    You can download the source for my F# AWS application from here. The remaining posts start on April 13, 2009, and run through today (with a few interruptions from me on other topics).

    Comments0

    Full story

  • Accessing S3 Through .NET

    (You can review my description of S3 here.) Because Amazon’s Simple Storage Service, S3, has been around for quite a while, the community has built a large number of libraries to access S3 programmatically. The C# space is pretty well crowded as well, and many folks wrote libraries that are good enough for their needs, then released those libraries to the world. The trick in picking an S3 library does not revolve around picking a best library. Instead, it involves finding one written by someone who had a similar set of needs. When looking for a library, think about how you want to add, update, and delete objects in S3. Write down the use cases. Then, download a set of libraries and keep messing with them until you find one that matches your needs. My planned usage involves: Create a bucket once, when the application first runs. (This step ...

    Comments0

    Full story

  • SimpleDB Delete

    This post uses Amazon’s SimpleDB C# library. Deleting a record is really simple. Again, this is to delete an ASP.NET MembershipUser from SimpleDB. To do this, you simply pass the ItemName to a DeleteAttributesRequest(). Because that name is unique within the domain, the values will go away. override this.DeleteUser(username, deleteAllRelatedData) =     PhotoWebInit.InitializeAWS     let simpleDb = PhotoWebInit.SimpleDBClient     let delAttr = new Model.DeleteAttributesRequest()     delAttr.DomainName <- PhotoWebInit.domainName     delAttr.ItemName <- username     let delResponse = simpleDb.DeleteAttributes(delAttr)     true Pretty easy, right? Next week, we’ll finish this up with a post on Simple Storage Service and a zipped copy of the source code (in case you want to see everything in one place).

    Comments0

    Full story

  • Using SimpleDB: Save a User

    With SimpleDB, you need to create a domain to store any data. Domain creation is a unique event in the life of an application, happening at install or some other infrequent event (addition of a new product line, client, etc. depending on how you partition data). 99+% of the time, the code will need to use the domain to Create, Retrieve, Update, or Delete data. These are more commonly known as CRUD operations. AWS stores the data as name-value pairs called attributes. The attributes have an additional value indicating if the value is replaceable/updatable or if the value can only be set of creation. Each item in the database has a name and a set of 1 or more attributes. In this post, I walk through how MembershipUser records are created and updated. This post uses Amazon’s SimpleDB C# library. The example has the following ...

    Comments0

    Full story

  • SimpleDB Domains

    Before you can access data in SimpleDB, you have to have a domain. Domain creation is fairly expensive in terms of time—up to 1/2 a second. Listing domains is really cheap—especially since you will normally have a maximum of 100 domains. When the application starts up, we want to check if the domains we need exist—if not, create them. Otherwise, mark an all clear so that the check doesn’t happen again. To handle all this work, we have a module named PhotoWebInit. The module instantiates a client capable of communicating with SimpleDB by reading the key and secret from configuration. Using that client, the code then checks to see if the domain we want, friseton_com, exists. OK—this code really looks to see if we have 0 domains or more. friseton_com is the first domain we need because if a user needs to be able to log in before any ...

    Comments1

    Full story

  • Filtering in a sequence

    It turns out that when many mechanisms exist to do a task, many things will work. Here is another way to handle the Seq.fold task from yesterday in a much cleaner way. It’s still neat to see all these workable options! Seq has another method, filter, which only returns those elements that return true for the supplied function. #light   open System.Collections.Generic   type MyType(propA:string, propB:int) =     member this.PropA = propA     member this.PropB = propB     override this.ToString() = System.String.Format("{0} {1}", this.PropA, this.PropB)   let typeSeq =     [|  new MyType("red", 4);          new MyType("red", 3);          new MyType("blue", 3);          new MyType("blue", 4);          new MyType("blue", 5);          |]   let filterVals theSeq propAValue =      theSeq |> Seq.filter(fun (a:MyType) -> a.PropA = propAValue)   printfn("%A") (filterVals typeSeq "red") printfn("%A"...

    Comments0

    Full story

  • Another use of Seq.fold: filtering

    Last night, I had to filter a bunch of entries in a sequence down to only those items that had a particular characteristic. My thought process went like this: “I have a list of objects. When I’m done, I want a list of objects that have property X, discarding everything else. Ah-ha, I want to fold the sequence into a List.” I had some other constraints, such as the other library I was using was written in C# and used List<T> instead of F# types. I don’t know that this is the best way to do things, but I’ll show it anyhow as an illustration of nifty stuff I’ve done lately. The code takes an array of some well-defined type and then filters on that type. In this case, the type has a formalized string * int tuple with names to make it useful from C#. You can place any ...

    Comments0

    Full story

  • AJAX and WCF

    Most of the information in this post applies to .NET 3.5. Code examples are in F# because I’m teaching myself F#. If you want C#, wait until I post the same material on Azure or buy my Effective REST Services via .NET book. I’m currently working on the finishing touches of an Amazon Web Services version of my PhotoWeb application. Because EC2 supports Windows, I’m building the whole thing for IIS, using F# as the programming language. One of the features of this application is that it uses AJAX to update metadata about the images on the screen. To handle AJAX, one commonly uses either ASMX or WCF. In .NET 3.5, the WCF team added some functionality to make AJAX a no-brainer via a ServiceHostFactory-derived class that just does the right thing and a few new attributes. This means no updates to web.config in order to get your service ...

    Comments0

    Full story

  • Seq.find—Neat!

    As I continue to build more F# code, I keep finding interesting usage of the language and its features. Today, I’m going to talk about Seq.find. Seq.find loops through a sequence (an IEnumerable in .NET speak) looking for some item that satisfies a function that returns a boolean. As soon as the function returns true, the iteration stops and the found item is returned. Maybe it will just be easier to show what the code looks like: #light   let thelist = [|("joe", 1); ("jim", 3); ("scott", 6); ("kenn", 29)|] let scottsNumber = thelist |> Seq.find(fun (a, b) -> a = "scott") |> (fun (a,b) -> b) printfn "%d" scottsNumber The code has an array of tuples. It then pipes that list into Seq.find. Because our tuple has two values, the function will also take a two value tuple. ...

    Comments0

    Full story

  • Something Interesting in F#

    I’m busy learning how to use SimpleDB. Since I can do the experimentation in F#, I am. Right now, I’m using the .NET SimpleDB client that Amazon has here. I had written the following code, which I only want to run when I discover that my SimpleDB domain does NOT exist:     let createDomain =             let createParam = new Model.CreateDomainRequest()             createParam.DomainName <- domainName             let response = SimpleDBClient.CreateDomain(createParam)             () A downside to this code is that it gets evaluated EVERY time. Creating a domain, even an existing one, takes several seconds from sending the request to receiving the response. Ideally, creation would only run as needed. What I really want is function type behavior for createDomain. That is, the actual work shouldn’t happen until I need it to. Then, I remembered that functions are first class citizens in F#. I transformed my code to this:         ...

    Comments0

    Full story

  • F# Seq.fold

    A lot of the business code we tend to write deals with taking some collection and producing some fact about that collection. Examples include: Taking all the line items in a sales order and producing a total value of the order. Concatenating a set of order lines to create an order. In F#, one can take a sequence of items and fold it to return another item representing some truth about that collection. This is done via the Seq.fold function. Typical invocation involves taking some collection, passing that collection via the pipeline operator, |>, to Seq.fold. Seq.fold then takes a function that has two values passed to it: an accumulator and the next value in the collection. Each value is folded into the accumulator in some fashion-- if summing up numbers or concatenating strings, the accumulator is just another number or string. On each successive iteration, the return value appears ...

    Comments0

    Full story

  • Method Overloading in F#

    In my goal to learn F# better, I'm doing all of my recreational development in the language. This gives me lots of learning opportunities (better known as WTF moments). I was implementing a MembershipProvider for an ASP.NET web site where the datastore is not SQL. By and large, MembershipProvider requires that you implement uniquely named methods. It does exposes a pair of abstract methods that one must implement. In C#, they look like this:     public abstract MembershipUser GetUser(         string username,         bool userIsOnline);       public abstract MembershipUser GetUser(         Object providerUserKey,         bool userIsOnline); These two methods seemed pretty natural to overload in F#. I just wrote these stubs:         override this.GetUser(providerUserKey: obj, userIsOnline: bool) : MembershipUser =             null           override this.GetUser(userName: string, userIsOnline: bool) : MembershipUser =             null The compiler didn't like this, telling me Duplicate definition of value 'AwsMembershipProvider.GetUser.3.override' No amount ...

    Comments0

    Full story

  • Utility to Replace \r\n with \n, in F#

    In my quest to learn F# better so that I might figure out when this tool makes sense, I have been trying to use the language whenever possible/feasible. Just such an opportunity happened while delving into Google App Engine. I found I could get rid of a little warning in the GAE development environment by converting all files from Windows style CRLF (\r\n) to a more Unix like LF (\n). Out came F# to solve this little problem! This application was moderately frustrating to write because of the puzzling syntax errors. I'm still working on getting the feel for F# and am trying to use it as my preferred hammer (realizing full well that "when all you have is a hammer, everything looks like a nail"). I have to admit, it was a fun little application to write!       1 #light     2 open System     3...

    Comments0

    Full story

  • F# assembly level attributes, AssemblyInfo.fs, and do()

    The project for this weekend is to create something that I can share with the rest of the web allowing one to create Web projects with F#. Part of doing this the right way is to include that handy dandy litany of assembly level attributes indicating things like assembly name, version, description, configuration, company, etc. In a C# project, this information appears in AssemblyInfo.cs. For my F# project, I figured that AssemblyInfo.fs is as good a place as any to start. So, how do you do this? Like in C#, assembly level attributes occur at file scope and have the word assembly: in front of the attribute. They wind up going into a file like so:   [<assembly: AssemblyVersion("1.0.0.0")>] [<assembly: AssemblyFileVersion("1.0.0.0")>]   Now, AssemblyInfo.fs wasn't going to have any types, and this frustrated the F# compiler a bit. After some tweaks, it coughed up a hint ...

    Comments0

    Full story

  • F# does a WCF Service

    I spent a large portion of my career working with WS-*/SOAP. So, once I understood how F# attributes worked, I thought it would be cool to see if I could write a WCF service. Nothing complex-- I just wanted to see if I could get HelloWorld up and running. Given that one can get a class running as a service with the right config and .svc file, this seemed like an easy task. First, I'll present the solution, then I'll talk about a couple of issues I ran into along the way to the solution. In F#, one adds attributes by placing a [<Attribute>] before the type or member. For WCF, we need the ServiceContractAttribute and OperationContractAttribute on the type and any exposed functions. The HelloWorld service can be written like this:       1 #light     2      3 namespace Service     4     ...

    Comments0

    Full story

  • Dealing with measurements in F#

    F# is clearly gearing itself for science and math. Well, most functional languages do since they frequently make it easy to express mathematical formulas naturally. One thing it does well is allow for measurements to be expressed using units. For example, let's say that we need to compute the velocity of an object falling towards Earth. Things fall towards Earth at 9.8 m/s^2. To compute the speed of an object falling towards Earth after falling a fixed distance, we would find that we can simply multiple distance * velocity and wind up with m^2/s^2. To find speed, we take the square root of the product. A common cause of bugs when performing this kind of calculation results from losing track of the units. How do we make sure that we at least know what the units are? For this kind of problem, F# introduces the Measure attribute. Measure allows a ...

    Comments0

    Full story

  1. 1
  2. 2
  3. »