Wednesday, 16 January 2008

F#: A simple oracle database application

The following is an example of how to connect to an Oracle database, retrieve some results and display them in a DataGrid in F#:
(* Use lightweight F# syntax *)
#light

#r @"System.Data.OracleClient.dll";;

(* Import managed assemblies *)
open System
open System.Data
open System.Data.Common
open System.Data.OracleClient
open System.Collections
open System.Text
open System.Windows.Forms

let form =
let f = new Form()
f.Visible <- true
f.TopMost <- true
f.Text <- "F# Query"
f.Height <- 600
f.Width <- 800
f
let grid =
let g = new DataGrid()
g.Dock <- DockStyle.Fill
g
form.Controls.Add(grid)
let connection_string = "Server=SID;Uid=johndoe;Pwd=password;"
let sql = "select * from tblwb_job"
let data_table = new Data.DataTable()
try
let connection = new OracleClient.OracleConnection(connection_string)
let command = new OracleClient.OracleCommand (sql, connection)
let adapter = new OracleDataAdapter(command)
let r = adapter.Fill(data_table)
connection.Close()
with
| :? System.InvalidOperationException as ex ->
ignore(MessageBox.Show(ex.Message))
| _ ->
ignore(MessageBox.Show("Unknown Exception"))

grid.DataSource <- data_table
do Application.Run(form)

Pretty sad that I couldn't play with Haskell as much as I want. At least, I can work on some functional language while working on real work.

Saturday, 5 January 2008

F#: Simple POSIX regular expression example


module Main (main) where

import System.IO
import Text.Printf
import Text.Regex.Posix
import Text.Regex.Base

text = "http://www.abc.com/xyz"
regex = "http://([^/]+)"

main = print (getFirstMatch( text =~ regex :: [[String]]))

getFirstMatch :: [[String]] -> String
getFirstMatch s = (s !! 0) !! 1

Haskell: Read the content of a file into a list of string

module Main (main) where

import IO
import System.Environment

main :: IO ()
main = do { x <- getArgs           
; hdl <- openFile (x !! 0) ReadMode           
; y <- readSources hdl []           
; print y }  
readSources :: Handle -> [String] -> IO [String]
readSources hdl s = do { t <- hIsEOF hdl                        
; if t then return s else do { x <- hGetLine hdl; readSources hdl (s ++ [x]) } }