Samples and Examples

Introduction

These samples are also available in the L Sharp repository at http://lsharp.sourceforge.net/download/.

HelloWorld.ls

Tradition says that Hello World must be the first sample.

;;; Hello World in L Sharp
(WriteLine Console "Hello World")

Factorial.ls

Computes the factorial of a number. Demonstrates recursion.

;;; L Sharp Factorial sample

;; Factorial
(= factorial (fn (n)
		(if (eql n 1) 
			1
			(* n (factorial (- n 1))))))
			
(prl (factorial 5))

Fibonacci.ls

Computes Fibonacci numbers using tree recursion.

;;; L Sharp Fibonacci sample

; Fibonacci, tree recursive style
(= fibonacci (fn (n)
		(if (eql n 0) 0
			(if (eql n 1) 1
				(+ (fibonacci (- n 1)) (fibonacci (- n 2)))))))

; Print the first 15 Fibonacci numbers
(to i 15 
	(prl (fibonacci i)))

Rss.ls

Retrieves news headlines from an RSS feed.

;;; Lists all the items from an RSS Feed

(reference "System.Xml")

(= news (new System.Xml.XmlDocument))
(call load news "http://www.theregister.co.uk/headlines.rss")
(foreach node (selectnodes news "/rss/channel/item/title") 
	(prl (innertext node)))

Greeting.ls

Displays a greeting depending on the time of day.

;;; Display a greeting depending on the hour

(if (< (Hour (Now DateTime)) 12) 
	(WriteLine Console "Good Morning") 
	(WriteLine Console "Good Afternoon") )

Guid.ls

Creates Globally Unique Identifiers.

;;; Generate a GUID
(prl (NewGuid System.Guid))

Hashtable.ls

Demonstrates the use of Hashtables.

;;; Hashtable Sample

(using "System.Collections")

;; Convert a list of lists to a Hashtable
(= foo (the Hashtable '(("a" "b") ("c" "d") ("e" "f"))))

;; Access an item
(Item foo "c")

;; Add an item
(set_Item foo "y" "z")

;; Convert the Hashtable back to a list
(prl (the Cons foo))

Iteration.ls

Demonstrates L Sharp's loop and iteration forms.

;;; Demonstrate some L Sharp iteration expressions

(for (= i 0) (< i 10) (++ i)
	(pr i))
	
(let i 0
	(while (< (++ i) 10) (pr i)))
	
(to i 10 (pr i))

(each x '(a b c) (pr x))

List.ls

Demonstrates the use of L Sharp Lists.

;;; Demonstrate some list manipulation
(= mylist '(a b c (d e f)))

(prl mylist)

(prl (first mylist))

(prl (rest mylist))

(prl (nth 3 mylist))

MessageBox.ls

Shows how to pop up a Message Box.

;;; Display a Windows Forms MessageBox

; Load the System.Windows.Forms assembly
(reference "System.Windows.Forms")

(using "System.Windows.Forms")
		
(Show MessageBox  "Dont you agree?" "LSharp is Cool")

Northwind.ls

Demonstrates access to a SQL database (the Microsoft Northwind Traders example).

;;; Northwind Database Example
(reference 
	"System.Data")

(using 
	"System.Data" 
	"System.Data.SqlClient")

;; Given a database connection string and a sql expression,
;; runs the SQL and returns a dataset
(= get-dataset (fn (connection-string sql)
	(do
		(Open (= cn (new SqlConnection connection-string)))
		(= cmd (new SqlDataAdapter sql cn))
		(= ds (new DataSet))
		(fill cmd ds)
		(dispose cmd)
		(dispose cn)
		ds)))
	


;; Of course your SQL Server wont have a blank SA password, so edit this
;; connection-string accordingly ..
(= connection-string "server=localhost;user ID=sa;password=;database=Northwind")

;; Get the list of customers
(= my-dataset (get-dataset connection-string "SELECT * FROM Customers"))
(= my-table (Item (Tables my-dataset) 0))

;; Filter the table further
(= filteredTable (Select my-table "CompanyName LIKE 'A%'"))

;; Print the rows
(each row filteredTable
	(prl (the Cons row)))

Queue.ls

Demonstrates how to use a Queue data structure.

;;; Queue Sample

(using "System.Collections")

(= my-queue (the Queue '(a b c d e f)))

(Enqueue my-queue 'g)
(Enqueue my-queue 'h)

(prl (the cons my-queue))

(to i (Count my-queue)
	(prl (Dequeue my-queue)))

Shell.ls

Shows how to launch another application such as Calculator or Internet Explorer.

;;; Demonstrates how to shell another process
(reference "System")
(using "System.Diagnostics")

(= shell (fn (app args)
	(do
		(= process (new Process))
		(set_EnableRaisingEvents process false)
		(set_FileName (StartInfo process) app)
		(set_Arguments (StartInfo process) args)
		(Start process))))

(shell "calc" "")
(shell "iexplore" "http://www.aws.net")
(shell "notepad" "c:\\junk.txt")

Try.ls

Exception handling.

;;; Example exception handling

; try executes its first form (the body) and if an exception is thrown
; executes its second form (the catch) with the variable it bound to
; the System.Exception object.
(try
	(throw (new System.NotImplementedException "foobar"))
	(prl (Format System.String "It failed, here's why: {0}" it)))

Whois.ls

A simple WHOIS client.

;;; A simple WHOIS Client
;;; Rob Blackwell 2004

(reference "System")

(using 
	"System.Net.Sockets"
	"System.Text"
	"System.Collections"
	"System.IO")

;; A lookup table of Top Level Domains and their associated WHOIS servers
(= whois-servers (the Hashtable 
	(quote ( 
		("net" "whois.networksolutions.com")
		("coop" "whois.nic.coop")
		("uk" "whois.nic.uk")
		("com" "whois.verisign-grs.com")
		("org" "whois.pir.org")
		("info" "whois.afilias.net")))))

;; Returns the WHOIS server responsible for a given domain
(= find-whois-server (fn (domain)
	(do
		(= tld (first (last (the Cons (Split domain (ToCharArray "."))))))
		(get_Item whois-servers tld))))

(= whois (fn (server query)
	(do
		(= buffer (GetBytes (ASCII Encoding) (Concat String query "\n")))
		(= stream (GetStream (new TcpClient server 43)))
		(Write stream buffer 0 (GetLength buffer 0))
		(= result (ReadToEnd (new StreamReader stream)))
		(Close stream)
		result)))

;; Usage is Lsharp.exe whois.ls domain, so domain is the third command line arg
(= domain (caddr (GetCommandLineArgs System.Environment)))

;; Find the correct whois server
(= nic (find-whois-server domain))

;; Print the whois information
(prl (whois nic domain))

String.ls

String examples.

;;; Recursively print substrings

;; Print succesive cdrs of a string 
(= funny-print (fn (n)
	(when n
		(prl (the String n))
		(funny-print (rest n)))))
						


;; Concatenate two strings
(= my-string (Concat String "Hello " "there"))

(funny-print my-string)

Stack.ls

Stack.

;;; Stack Sample

(using "System.Collections")

(= my-stack (the Stack '(a b c d e f)))

(Push my-stack 'g)
(Push my-stack 'h)

(prl (the Cons my-stack))

(to i (Count my-stack)
	(prl (Pop my-stack)))

Sound.ls

The L Sharp Sound Library.

;;; Sound Sample

(reference "Lsharp.Libraries")

(= play-sound (fn (filename)
	(Play LSharp.Libraries.Sound filename)))

(play-sound "c:\\windows\\media\\tada.wav")

SortedList.ls

Showss the use of SortedList.

;;; SortedList Sample

(using "System.Collections")

;; Convert a list of lists to a Hashtable
(= foo (the SortedList '(("c" "d") ("e" "f") ("a" "b"))))

;; Access an item
(Item foo "c")

;; Add an item
(Add foo "y" "z")

;; Convert the Hashtable back to a list
(prl (the Cons foo))

Smtp.ls

Shows how to programmatically send an email message.

;;; Sends an SMTP email message

(reference "System.Web")

(using "System.Web.Mail")

; Use this SMTP Mail server
(= *mailserver* "localhost")

(= send-mail (fn (to-address from-address subject body)
	(do	
		(set_SmtpServer SmtpMail *mailserver* )

		(= mailMessage (new MailMessage))

		(set_To mailMessage to-address)
		(set_From mailMessage from-address)
		(set_Subject mailMessage subject)
		(set_Body mailMessage body)

		(Send SmtpMail mailMessage))))


(send-mail "fred.bloggs@hotmail.com" "rob.blackwell@aws.net" "Test Subject" "Test Body")

Regex.ls

Demonstrates the use of regular expressions

;;; Regular expression example

(reference "System")

(using "System.Text.RegularExpressions")

; Returns true if search appears in buffer
(= find (fn (buffer search)
		(do 
			(= regex (new Regex (Concat System.String ".*" search)))
			(Success (Match regex buffer)))))

; Define a regular expression for matching URLs
(= urlExpression (new Regex "^(?<proto>\\w+)://[^/]+?(?<port>:\\d+)?/"))

; Does it match ?
(prl (Match urlExpression "http://www.aws.net:8080/"))

; Pull out the protocol and port
(prl (Result (Match urlExpression "http://www.aws.net:8080/") "The protocol is ${proto} and the port is ${port}"))


Http.ls

Demonstrates how to use HTTP GET and POST to access resources on the Web.

;;; HTTP GET and POST

(reference "System" "System.Web")

(using "System.IO" "System.Net" "System.Web" "System.Text")

;; ASCII encodes a Byte Array
(= ascii-encode (fn (byteArray)
	(do
		(GetString (ASCII Encoding) byteArray))))


;; HTTP POST to a url
(= http-post
	(fn (url postdata)
		(do
			(= uri (new Uri url))
			(= request (Create WebRequest uri))
			(set_Method request "POST")
			(set_ContentType request "text/xml")
			(set_ContentLength request (Length postdata))
			(= writer (new StreamWriter (GetRequestStream request)))
			(Write writer postdata)
			(Flush writer)
			(Close writer)
			(= response (GetResponse request))
			(= reader (new StreamReader (GetResponseStream response)))
			(= result (ReadToEnd reader))
			result)))

;; Retrieve a web resource using HTTP GET
(= http-get
	(fn (url)
		
		(do
			(= uri (new Uri url))
			(= request (Create WebRequest uri))
			(set_Timeout request 120000)
			(set_Accept request "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*")
			(set_KeepAlive request false)
			(set_UserAgent request "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)")
			(set_Method request "GET")
			(= response (GetResponse request))
			(= reader (new StreamReader (GetResponseStream response)))
			(= result (ReadToEnd reader))
			(Close reader)
			(Close response)
			result)))


;; Retrieve and print the Slashdot home page
(prl (http-get "http://slashdot.org/"))




File.ls

Defines some useful functions for manipulating files.

;;; L Sharp File Sample

(using "System.IO")

;; Copy a file
(= copy-file (fn (from to)
	(do
		(= fileInfo (new FileInfo from))
		(CopyTo fileInfo to true))))

;; Move a file		
(= move-file (fn (from to)
	(do
		(= fileInfo (new FileInfo from))
		(MoveTo fileInfo to))))

;; Delete a file		
(= delete-file (fn (filename)
	(Delete File filename)))

;; Read a file, returning its contents as a string
(= read-file (fn (filename)
	(do
		(= textReader (new StreamReader filename))
		(= buffer (ReadToEnd textReader))
		(Close textReader)
		buffer)))


Directory.ls

Demonstrated some simple functions for manipulating directories. Note how recurse-directory takes a function as an argument; that function is applied to all matching files.

;;; L Sharp Directory sample
(using "System.IO")

;; Rename / move a directory
(= move-directory (fn (from to)
	(do
		(= directoryInfo (new DirectoryInfo from))
		(MoveTo directoryInfo to))))

;; Recurse the given directory applying the the function 
;; or method fun to each file found
(= recurse-directory (fn (dir pattern fun)
	(do
		(= directoryInfo (new DirectoryInfo dir))
		(= files (GetFileSystemInfos directoryInfo))
		(each file files 
			(if (eql (GetType file)	(typeof DirectoryInfo))
					(recurse-directory (FullName file) pattern fun)))

		(= files (GetFileSystemInfos directoryInfo pattern))
		(each file files 
			(if (eql (GetType file)	(typeof FileInfo))
					(fun file)))
	)))

;; Define a function to be called on each file
(= myfun (fn (n)
	(prl (format string "Filename is {0}" (FullName n)))))

;; Recurse the directory calling fun on each dll file
(recurse-directory "c:\\windows\\system32" "*.dll" myfun)

;; Recurse the directory calling the method FullName on each file 
(recurse-directory "c:\\windows\\system32" "*.dll" 'FullName)

Squares.ls

;;; List the squares up to n
(= squares (fn (n) 
	(to i (+ n 1)
		(prl (format string "The square of {0} is {1}" i (* i i))))))

(squares 12)