Posts tagged ‘F#’

Poker : Programming Problem

Although it has been a while since Brian posted the poker problem in his blog, I haven’t got the chance to look at it until I came across in ProjectEuler Problem 54. It is not the elegant or best solution at all, but just wanted to join the crew and can confirm it works with the problem’s 1000 games’ dataset.

Hope this helps.

#light
(* Problem 54 *)
type suit = |Spades |Hearts |Clubs |Diamonds 
type card=  |Ace = 14 |Two = 2  |Three =3  |Four = 4 |Five = 5 |Six = 6 
            |Seven =7  |Eight = 8 |Nine = 9 |Ten = 10 |Jack = 11 |Queen =12 |King  =13
type acard = (card * suit)  
 
let carder x:card= enum x
 
let card_value = function
    | 'A' -> card.Ace
    | 'K' -> card.King
    | 'Q' -> card.Queen
    | 'J' -> card.Jack  
    | 'T' -> card.Ten
    | c ->  carder(System.Int32.Parse(c.ToString()))
 
let suit_value = function
    | 'S' -> Spades
    | 'H' -> Hearts    
    | 'C' -> Clubs
    | 'D' -> Diamonds    
    | a -> invalid_arg (a.ToString())
 
let Create (str: string) :acard = (card_value str.[0],suit_value str.[1])
 
let isstraigh (mycards:acard list)  = 
    let mycards = List.sort_by (fun (a,b) -> a,b) mycards
    let rec isstr previouscard mycards   (straightlist : acard list) =
        if straightlist.Length >= 5 then straightlist
        else match mycards with  
                | cur :: rest -> if int (fst cur) = int ((fst previouscard)) + 1 then isstr cur rest  (cur::straightlist)
                                 else isstr cur rest  []                           
                | _ -> []
    let head = List.hd mycards
    isstr head (List.tl mycards) [head]
 
let pairl (mycards : acard list) groupfunction minelementCount =
                 mycards |> Seq.group_by groupfunction
                         |> Seq.filter (fun a -> Seq.length (snd a) >= minelementCount)
                         |> Seq.to_list
                         |> List.unzip
 
 
type Ranks =
    | Highest of card
    | Pair of  card
    | TwoPair of card*card
    | Three of card
    | Straight of card
    | Flush of card 
    | FullHouse of  card*card
    | Four of  card
    | StraightFlush of card
 
type Player = |One |Two  |Noone
 
let rank (mycards :  acard list) =     
    let traverseL  (l :'a list)  = if not l.IsEmpty then l  |> List.hd |> Seq.to_list
                                   else []                            
    let isflush mycards = snd (pairl mycards snd 5)  |> traverseL
 
    let FofF l = traverseL l |> List.hd |> fst
 
    let flush = isflush mycards
    let straight = isstraigh mycards
 
    let ispair count= pairl mycards fst count                                                             
 
    let four,fours = let f,s = ispair 4 
                     f,s|> traverseL
    let three,threes = ispair 3 
    let two,twos = ispair 2
 
    let maxcard c = fst (List.max c)
 
    if not flush.IsEmpty && not straight.IsEmpty then StraightFlush(maxcard flush),flush
    elif  not fours.IsEmpty then Four(four.Head),fours
    elif not threes.IsEmpty && not twos.IsEmpty && FofF twos <> FofF threes then FullHouse(two.Head, three.Head), List.append (threes |> traverseL) (traverseL twos)
    elif not flush.IsEmpty then Flush(maxcard flush),flush
    elif not straight.IsEmpty then Straight(maxcard straight),straight
    elif not three.IsEmpty then Three( three.Head), threes |> traverseL
    elif List.length two = 2 then TwoPair(two.Head,two.Tail.Head),Seq.append (twos.Head) (twos.Tail.Head) |> Seq.to_list
    elif not (twos |> traverseL).IsEmpty then Pair(two.Head), twos |> traverseL
    else Highest(maxcard mycards), [List.max mycards]
 
let play input =
    let convert (line: string) = let l = line.Split([|' '|])                                  
                                 [|[for j in 0 .. 4 do yield Create( l.[j])]; [for j in 5 .. 9 do yield Create( l.[j])]|]                                                                  
    let playercrds = convert input              
    let rec iswinner pcards=               
                let ranks,rankcards = pcards |> Array.map (rank)  |> Array.unzip
 
                let removecards (mainlist) (toberemoved)  =                         
                        mainlist |> Array.map2 (fun rem main-> main |> List.filter (fun c->
                                List.fold_left(fun ac x-> if x = c then ac && false else ac && true) true rem)) toberemoved
 
                if ranks.[0]>ranks.[1] then One
                elif ranks.[0]<ranks.[1] then Two
                else iswinner  (removecards  pcards rankcards) 
 
    iswinner playercrds
 
 
play  "5H 5C 6S 7S KD 2C 3S 8S 8D TD" 
play  "5D 8C 9S JS AC 2C 5C 7D 8S QH"
play  "2D 9C AS AH AC 3D 6D 7D TD QD"
play  "4D 6S 9H QH QC 3D 6D 7H QD QS"  // prob pair queens look at the highes
play  "2H 2D 4C 4D 4S 3C 3D 3S 9S 9D" 
 
play  "2H 2D 4C 4D 4S 2H 2D 4C 4D 4S" 
 
play  "TH 8D 6C 4D 3S TH 8D 6C 4D 4S" 
 
 
 
let rdinput =   use file = System.IO.File.OpenText("poker.txt")
                let p1count = ref 0  
 
                while not file.EndOfStream do
                 if play (file.ReadLine()) = One then p1count := !p1count+1
 
                file.Close()
                !p1count

Power of Functional Programming, its Features and its Future

Power of Functional Programming

Functional programming is one the oldest of major programming paradigms. Functional languages have been with us for a while. Languages like Lisp, Scheme, ML, OCaml, Haskell, Erlang and F# have well built compilers and tools and large user and development communities. However, the early success of the imperative programming languages made the procedural languages extremely popular for more than three decades. This lead to the rise of the object-oriented paradigm and formed the basis of commercial software development. Object oriented programming is still the most popular paradigm today.

Functional programming is a programming paradigm that uses the functions in their real mathematical sense. This means that functions are only computation objects where there is no mutable data and state information. This way it is more close to mathematical expressions. In contrast to imperative programming that is desperately dependent on the state of the objects, functional programming views all programs as collections of functions that accept arguments and return values.

Modern functional programming languages have a number of different techniques to help program development. That includes but not limited to the

  • Powerful typing systems : It is accomplished with the support of polymorphism, and type inference
  • Higher order functions: The higher-order functions are based on the concept of the first class values as functions mainly functions are actually like data.
  • Implicit recursion: Implicit recursion is supported functional languages through the powerful functional data structures and also with higher-order functions such as fold, map and filter.

In programming languages, static typing means the type of expression is determined at compile by a technique called static program analysis. On the other hand dynamically typed languages, determines the types at the runtime by the aid of a runtime type checker. Personally, I like everything to be typed at the compile time with an extensive support of polymorphic types; because it allows seeing the errors at compile time and also it gives an optimised performance because there is no need for a runtime type checker. Luckily most of the functional languages benefit from the polymorphic statically typed systems.

Pureness is another concept applied by some functional languages like Haskell. On the other hand, it might be a style of programming even if it is not forced by the compiler. In pure functional programming, side effects are not allowed in the program with immutable variable and no loops. Immutability means that when a value is assigned to an identifier (not a variable), it cannot change anymore. Loops can be achieved with recursive functions. This style is a bit more difficult to program and read as well, but the benefits could be massive. For instance, it might be possible to optimise the compiled code for multiple cores, because of the compositionality of the functions that form the program.

The Features of Functional Programming

Functional Programming is not all about functions treated as first class values and immutable state. Functional programming also provides powerful features that every programmer should benefit.

Lambda calculus is a formal system designed to investigate function definition, function application and recursion. Lambda calculus could be used to define a computable function. Lambda calculus is used to develop a formal set theory. Function can be passed as an argument to other functions. There is another concept called curried functions when using lambda functions. The function reduces the term and returns another function with the normal form. This is called curried functions. In the lambda calculus, functions can only be created using another method, with higher-order functions and currying, another function creation is provided. A function in curried form is called partial application.

The calculus has only functions of one argument. In the curried function systems, a function with multiple arguments is expressed using a function whose result is another function. Every argument is reduced by default and returns a function.

Pattern matching is another powerful concept that functional and logic languages sport. It is used for assigning values to variables and for controlling the execution flow of a program. Pattern matching is used to match patterns with terms. If a pattern and term have the same shape then the match will succeed and any variables occurring in the pattern will be bound to the data structures which occur in the corresponding positions in the term.

Recursion is a mechanism for iterating an instruction or simply for a code reuse. By recursion it is possible to write a compact program that can help generalization. It is mainly used in functional programming.

Nowadays collections are the most important data structures when writing programs in any programming languages because of the big datasets. In most of the functional languages there are special functions to make the programmers jobs easy. By the usage of first class functions and those methods ends up in a good way to handle the collections. Some of those higher-order functions are map, fold, filter etc.

  • Map : applies the function passed to each element of the collection. Resembles to for each loops for collections in procedural languages.
  • Fold : applies the function to each element while sharing a resulting object. One common uses us to apply a sum operation to each member. It is similar to SQL aggregate functions but we pass the applying function.
  • Filter : applies the filter function to each member of the collection and returns a list of object satisfying the conditional function.

Some pure languages implement those higher-order functions in a continuation style. But it could be implemented by simple loops in unpure languages as well.

Functional languages help rapid prototyping with the aid of powerful type systems and usually with an interactive window that allows executing expressions one or more at a time. It enables to code complex algorithms without ignoring the mathematical representation. It is much easier to create domain-specific languages (DSLs). It improves the productivity of the developer.

DSLs are specific programming languages made for use in a specific application domain. Programs written with a DSL are more clear and readable than those written with general-purpose languages. DSLs are more declarative than the imperative languages and they focus on the problem rather than the rules of the language. Meta programming is building a program which manipulates the syntactic structures of other programs. DSLs and meta programming are closely related to each other. It is possible to build a domain specific language by the meta programming features of a language.

The Future of Functional Programming

Object oriented paradigm is crucial in programming current industrial applications. A functional language has usually been considered as an academic language but I believe that this is going to change in the real feature, because functional programming has a big potential in this demanding industry. The expressiveness, powerful unique concepts such as laziness, immutability, powerful pattern matching, continuations etc. and the elegant style of programming makes the implementation of some tools easier than other paradigms. Tools such as static analysis tools, high-level modelling, compilation, interpretation and verification tools are one of the target areas of functional programming. Moreover one of the todays hot topics domain specific languages, eventually meta programming and need for a “uniformed single language” for all solutions makes functional programming very important. Those tasks could be implemented with other languages as well, but functional languages fit better than the others. Also the distribution of tasks in multi-cores or multiple machines might be possible with functional programming if the program is written in an immutable style.

Considering today’s facts, running systems, interoperability with the systems, non-functional world; using functional programming shouldn’t mean staying functional all the time. For the difficulty of some problems and previous experience of the developers it is inevitable to use procedural and object oriented paradigms. That’s how the mix functional object oriented programming emerged and affected the programming languages.

Not surprisingly, some companies already work with functional programming in industry. For the moment their main areas of development is design, modelling, specification, or build compiler tools. But this is yet to change and augment.

Book Review-Foundations of F#

“Foundations of F#” is written by Robert Pickering who is a programmer and author living and working in Paris, France as he says. I think his enthusiasm in F# and .NET Framework made him to write this book. I really enjoyed reading his book and learned some new tricks in F# as well.

Review

fsfound.jpg

“Foundations of F#” is a great introductory book for F# with some advanced samples. For those who are unfamiliar with functional programming, this book gives the notions of functional programming in all aspects while giving samples in the greatest platform with great language F#.

This book includes functional, imperative and object oriented programming paradigms giving great samples. Robert Pickering also focuses to the imperative programmers by giving the usage differences in F#. He introduces a wide range F# data structures from simple arrays to quotations with great explanations.

This book gives a lot of information on .NET Framework including the latest additions .NET Framework 3.0 and 3.5. Samples with LINQ and Windows Presentation Foundation fulfil this area. If you are unfamiliar with .NET Framework, don’t worry this book gives what you need to know about .NET framework in many different areas including network programming, web programming, database programming, and windows programming with clear and explanatory samples using relevant screenshots. The samples are unique and useful, it’s not the examples that you can find on the web, and it’s more specialised and focused on techniques specific to F#

Personally I most liked Language Oriented Programming chapter which gives very specific features and usage tricks to F# to make the most of the language. It’s a must have book in your bookshelf if you are interested in functional programming on .NET Framework