Recently in Functional programming in general Category

Standard ML und Haskell

| No Comments | No TrackBacks
Derzeit erarbeite ich mir die Grundlagen der funktionalen Programmiersprache Standard ML (Studium - Fortgeschrittene Konzepte funktionaler Programmierung). Da ich schon ein bischen Haskell kann, konnte ich es mir nicht nehmen die Aufgaben auch in einer Haskell-Version zu implementieren. Wie man sieht sind sich SML und Haskell (zumindest bisher in den Grundlagen) sehr ähnlich. Allerdings ist die Syntax von Haskell an einigen Stellen etwas "fortgeschrittener". Es werden in Haskell insgesamt etwas weniger Schlüsselwörter (z.B. val, end, fun, fn...) und Kommas in der Syntax verwendet. Ausserdem gibt es in Haskell die (optionale) Möglichkeit die Typen einer Funktion explizit hinzuschreiben. Was leserlicher ist und zudem Programmierfehler vermeidet. Was ich bisher bei SML vermisse sind auch die sog. Pattern Guards die es in Haskell gibt. I.A. gefällt mir bisher Haskell besser als SML, u.A. auch da Haskell sich "pur funktional" schimpft während SML auch von imperativen Konzepte explizit Gebrauch macht. Aber soweit bin ich in SML noch nicht. Hier ein paar Funktionen in SML und in Haskell im Vergleich:

Standard ML:

fun v_v_mult [] _ = 0
  | v_v_mult _ [] = 0
  | v_v_mult vs ws = 
    let val prods = map (fn (v, w) => v * w) (zip vs ws)
     in foldr op+ 0 prods
    end

Haskell:

v_v_mult :: (Num a) => [a] -> [a] -> a
v_v_mult [] _ = 0
v_v_mult _ [] = 0
v_v_mult vs ws =
  let prods = map (\(v, w) -> v * w) (zip vs ws)
   in foldr (+) 0 prods

Standard ML:

fun m_v_mult [] _ = []
  | m_v_mult (vs::vss) ws = 
    let val sum = v_v_mult vs ws
     in sum :: m_v_mult vss ws
    end

Haskell:

m_v_mult :: (Num a) => [[a]] -> [a] -> [a]
m_v_mult [] _ = []
m_v_mult (vs:vss) ws =
  let sum = v_v_mult vs ws
   in sum : m_v_mult vss ws

Standard ML:

fun m_m_mult _ [] = []
  | m_m_mult vss (ws::wss) =
    let val sums = m_v_mult vss ws
     in sums :: m_m_mult vss wss
    end

Haskell:

m_m_mult :: (Num a) => [[a]] -> [[a]] -> [[a]]
m_m_mult _ [] = []
m_m_mult vss (ws:wss) =
  let sums = m_v_mult vss ws
   in sums : m_m_mult vss wss

Standard ML:

datatype ''a multi 
  = EMPTY
  | ELEM of ''a
  | UNION of ''a multi * ''a multi

Haskell:

data (Eq a) => Multi a
  = Empty
  | Elem a
  | Union (Multi a) (Multi a) 
  deriving Show

Standard ML:

fun number (EMPTY) _ = 0
  | number (ELEM x) w = if x = w then 1 else 0
  | number (UNION (x,y)) w = (number x w) + (number y w)

fun test_number w = 
  number (UNION (
    EMPTY, 
    UNION (
      ELEM 4,
      UNION (
        ELEM 6,
        UNION (
          UNION (
            ELEM 4,
            ELEM 4
          ),
        EMPTY)
      )
    )
  )) w

Haskell:

number Empty _ = 0
number (Elem x) w = if x == w then 1 else 0

test_number w = 
  number (Union 
    Empty
    (Union 
      (Elem 4)
      (Union
        (Elem 6)
        (Union
          (Union
            (Elem 4)
            (Elem 4)
          )
        Empty)
      )
    )
  ) w

Standard ML:

fun simplify (UNION (x,y)) = 
    let fun is_empty (EMPTY) = true
        | is_empty _ = false
       val x' = simplify x
       val y' = simplify y
     in if (is_empty x') andalso (is_empty y')
        then EMPTY
       else if (is_empty x')
        then y'
       else if (is_empty y')
        then x'
       else UNION (x', y')
    end
  | simplify x = x

Haskell:

simplify (Union x y) 
    | (isEmpty x') && (isEmpty y') = Empty
    | isEmpty x' = y'
    | isEmpty y' = x'
    | otherwise = Union x' y'
  where 
    isEmpty Empty = True
    isEmpty _ = False
    x' = simplify x
    y' = simplify y
simplify x = x

Standard ML:

fun delete_all m w =
  let fun delete_all' (ELEM x) = if x = w then EMPTY else ELEM x
      | delete_all' (UNION (x,y)) = UNION (delete_all' x, delete_all' y)
      | delete_all' x = x
   in simplify (delete_all' m)
  end

Haskell:

delete_all m w = simplify (delete_all' m)
  where
    delete_all' (Elem x) = if x == w then Empty else Elem x
    delete_all' (Union x y) = Union (delete_all' x) (delete_all' y)
    delete_all' x = x


Standard ML:

fun delete_one m w =
  let fun delete_one' (UNION (x,y)) = 
      let val (x', deleted) = delete_one' x 
       in if deleted 
        then (UNION (x', y), deleted)
        else let val (y', deleted) = delete_one' y 
           in (UNION (x, y'), deleted)
          end
        end
      | delete_one' (ELEM x) = 
        if x = w then (EMPTY, true) else (ELEM x, false)
      | delete_one' x = (x, false)
      val (m', _) = delete_one' m 
    in simplify m'
  end

Haskell:

delete_one m w = do
    let (m', _) = delete_one' m 
      simplify m'
  where
    delete_one' (Union x y) = 
      let (x', deleted) = delete_one' x 
       in if deleted 
        then (Union x' y, deleted)
        else let (y', deleted) = delete_one' y 
             in (Union x y', deleted)
    delete_one' (Elem x) = 
        if x == w then (Empty, True) else (Elem x, False)
    delete_one' x = (x, False)

I've mentioned this book once before.

wizard.jpgStructure and Interpretation of Computer Programs has been MIT's introductory pre-professional computer science subject since 1981. It emphasizes the role of computer languages as vehicles for expressing knowledge and it presents basic principles of abstraction and modularity, together with essential techniques for designing and implementing computer languages. This course has had a worldwide impact on computer science curricula over the past two decades.

You can find the online videos and the free online book right here. For the case the ftp servers are busy you can download them from my own pub ftp instead (ftp.buetow.org/pub).

41QUtMNiIqL.jpg I've just ordered a new book (in german language) called "Funktionale Programmierung: Sprachdesign und Programmiertechnik " (in english "Functional programming: Language design and programming techniques"). This book is for people who know already a little bit about functional programming but want to dig deeper a little bit! It is demonstrating lots of stuff using functional programming languages such as Haskell and Opal.

'Programming Haskell' online lectures

| 1 Comment | No TrackBacks

haskell.png I found a great series of free haskell lectures online at http://www.cs.nott.ac.uk/~gmh/book.html#videos. The referent is going through all the chapters of the book 'Programming Haskell'. The videos are pretty good and atm I am enjoying watching them. You should give them a try as well! I think you don't even need to buy the book in order to understand everything.

Update: I put those videos on my pub FTP server for download: ftp://ftp.buetow.org/pub/OnlineLectures/ProgrammingHaskell/

41VPCK8QCXL._SS500_.jpgDuring Christmas break I read the book "Structure and Interpretation of Computer Programs - Second Edition" (by Harald Abelson and Garald Jay Sussman with Julie Sussman).

"The book should be read by every self-respecting computer scientist. Because of its clarity, simplicity, and wit, this work is highly recommended to anyone seeking an understanding of the emerging pradigms of computer science"

-- Mitchell Wand, American Scientist

This book handles all the topics using the dialect of Lisp called Scheme. It is impressive how simple a syntax and the interpreter and how powerfull the corresponding language can be. The book is mainly dealing with funcional programming techniques. I should overthink Fype, which is my own language for which I wrote an interpreter for.

Introducing sload.buetow.org

| No Comments | No TrackBacks

haskell.pngIn order to learn functional programming and to calculate server loads at work I programmed in my spare time this small tool using the purely functional programming language named Haskell! SLoad stands for Serverload. And this is exactly what it is for. SLoad only uses basic parameters (current CPU peak, current requests per second) in order approximate the future need of servers. The website is located at sload.buetow.org.

I am looking for a way of doing fuzzy string matching using the Haskell programming language. I want to parse the user's text input (which is a normal natural english sentence). The user may will have errors in his text, which should get recognized and replaced automatically by my program. I think the easiest way would be calculating the 'Levenshtein distance' to all known words and use the word with the smallest distance. Although, this is not really fuzzy logic (fuzzy logic depends, in my view, more on the context of the sentence which is written), I think it is a good starting point in order to get an initial version working. According to the Wikibook the Haskell implementation would be as easy as this:

levenshtein :: String- > String -> Int
levenshtein s t = 
    d!!(length s)!!(length t) 
    where d = [[distance m n|n<-[0..length t]]|m<-[0..length s]]
          distance i 0 = i
          distance 0 j = j
          distance i j = minimum [d!!(i-1)!!j+1, 
                                 d!!i!!(j-1)+1, d!!(i-1)!!(j-1) 
                                  + (if s!!(i-1)==t!!(j-1) 
                                     then 0 else 1)]

This method may be too slow if I've to compare each word with about serveral thousands words. Hrrm.

Or using another implementation, because:
The implementations of the Levenshtein algorithm on this page are illustrative only. Applications will, in most cases, use implementations which use heap allocations sparingly, in particular when large lists of words are compared to each other.

Yet another way would be implementing a Fuzzy Logic Library (as learned in the Neuronal Fuzzy Networks lecture @ Aachen University of Applied Sciences) from scratch.

Progress in Haskell

| 1 Comment | No TrackBacks

My first real program written in Haskell is growing. It is forming valid english sentences.

makeSentences = do
	let pronoun = SgI 
        in print $ (pronounForm pronoun) 
           +++ (futureForm pronoun $ IrregularVerb 
                         "go" "went" "gone") 
           +++ (superlative $ RegularAdjective "fast")
	let pronoun = SgHe 
        in print $ (pronounForm pronoun) 
           +++ (presentForm pronoun $ IrregularVerb 
                         "go" "went" "gone") 
           +++ (comparative $ RegularAdjective "fast")
	let pronoun = PlWe 
        in print $ (pronounForm pronoun) 
           +++ (pastForm pronoun $ RegularVerb "watch") 
           +++ (comparative $ IrregularAdjective 
                         "good" "better" "best")

The output of this small program is as follows:

*Main> makeSentences
"I will go the fastest"
"he goes faster"
"we watched better"

real-world-haskell.jpgSo far the program handles pronouns, regular verbs, irregular verbs, regular adjectives and irregular adjectives with all of their exceptions. The program is less then 200L. Since I am used to C/C++/Perl and Java, programming in Haskell forces me to rethink the way of programming. It's a great experience. I still 've much to learn. And my Real World Haskell book I've only finished half yet :)

Learning functional programming

| 4 Comments | 1 TrackBack

The last weeks I started (slowly but constantly) to learn functional programming using Haskell. First, I started with the functional programming practices (available as videos) of the RWTH Aachen (University). However those practices aren't so good if you don't have the lecture itself as well. Afterwards I was reading most of the Yet Another Haskell Tutorial and did most of the practices listed inside. I did this until I found out about the book Real World Haskell, which is also available for free as HTML pages. I decided a hard cover book is much nicer and it is supporting the authors, so I ordered myself a copy of this. While waiting for it, I found a 15 year old book about Informatics in my shelf.

vorlesung-informatik.jpg

The last ~150 pages teach how to functional program using the Gofer Programming Language. While waiting for Real World Haskell I am reading how to program in Gofer at the moment. Gofer can be seen as a very light version of Haskell. So if I learn Gofer, then I also learn Haskell. Today, Haskell is 100% compatible to Gofer plus more.

One of my long term goals may be reimplementing my AI IRC Bot in Haskell. At the moment, the bot is written in Perl.

About this Archive

This page is an archive of recent entries in the Functional programming in general category.

Fun is the previous category.

Fype is the next category.

Find recent content on the main index or look in the archives to find all content.