A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Friday, September 11, 2009

F you

I'm talking about F#, what'd you think I was talking about? I can't tell if it's, Functional programming itself or F# that's causing me more pain. I wasn't blessed to deal with Lisp or a derivative in college so it's only as an adult that I'm trying to wrap my brain around it. Imperative and declarative programming, I think I have down solid. Python and this Johnny-come-lately C# led me to believe I should be okay with the concepts of functional programming. Visual Studio 2010 has full-fledged support for F# and a nifty tutorial which compiles and runs just fine. However, my ability to crib from that to build out my own solutions for Project Euler has been less than spectacular. After starting complex, I've distilled my problem down to "how do I append another element to a list." The damnable thing, is that they have an example right there in the tutorial of how to do it in F#.


#light
// List of best friends.
let bffs = [ "Susan"; "Kerry"; "Leslie"; "Maria" ]

// Bind newBffs to a new list that has "Ginger" as its first element.
let newBffs = "Ginger" :: bffs


Monkey see, monkey do but I wanted to work with integers and append an integer to the end.


// List first fibbonaci numbers.
let fib = [ 1; 1; 2; 3; 5; 8 ]

// Bind fibNext to a new list that has 13 as its last element.
let fibNext = fib :: 13


That throws a syntax error though: "This expression has type int but is here used with type int list list" Some hits with Google for that but no one seems to have as elementary of a sample as I'm working with. Logically, it makes me think the type is wrong with 13.


// List first fibbonaci numbers.
let fib = [ 1; 1; 2; 3; 5; 8 ]
let thirteen = [ 13 ]

// Bind fibNext to a new list that has 13 as its last element.
let fibNext = fib :: thirteen

That results in the even more maddening error of "Type mismatch. Expecting a int list list but given a int list. The type 'int list' does not match the type 'int'" Sooo, it's expecting an int list list but I only gave it an int list... However, it's at least list-like so thanks to this link I at least see that I can concat two lists with the @ operator so the following compiles so it must work

let fibNext = fib @ thirteen

Blessedly, it does and I'm back in to defiling F# with my unwashed hands. TODO: find and read an article like Dive into Python for F#

No comments: