Sep 24, 2010

Sorting a list in haskell

We can write a hascell coding for sort a list in assending or desending order.

quickSort []=[]
quickSort [x]=[x]
quickSort (x : xs) = (quickSort less) ++ (x : equal) ++ (quickSort more)
where less = filter (< x) xs equal = filter (== x) xs more = filter (> x) xs

write this in a hakell file and load it into the intepreter. Now type;
quickSort ["i", "have", "a", "thing", "for", "linux"]
It will give the output like this.

But if you type as;
quickSort ["I", "have", "a", "thing", "for", "Linux"]
you will get the output as;
this. Sorting is done by looking at the ASCII values and capital letters got less value than the others. So to avoid that thing we must ignore the case of the characters.

Module is a group of related functions in a singe package. We can use functions for our codings without implementing them. The only thing we must do is import the correct module and call the correct function. There are many ways of importing modules.

import Data -- import everything from Data module
import Data.List -- import everything exported from Data.List
import Data.Char (toLower, toUpper) -- import only the functions toLower and toUpper from Data.Char

Haskell is depend on indentation. So you must think about the indentation when you are writing a haskell coding. Basic things are like this.
let x = a
y = b

do foo

where x = a
y = b

case x of
p -> foo
p' -> baz

myFunction firstArgument secondArgument =
do foo

myFunction firstArg secondArg = do foo

Foo and bar must inline
If else statment --

if foo
then do first thing
second thing
third thing
else do something else

No comments:

Post a Comment

Your comments are always welcome ...