SlideShare a Scribd company logo
Real World Haskell:
     Lecture 7

   Bryan O’Sullivan


     2009-12-09
Getting things done




   It’s great to dwell so much on purity, but we’d like to maybe use
   Haskell for practical programming some time.
   This leaves us concerned with talking to the outside world.
Word count


   import System . E n v i r o n m e n t ( getArgs )
   import C o n t r o l . Monad ( f o r M )

   countWords p a t h = do
     c o n t e n t <− r e a d F i l e p a t h
     l e t numWords = l e n g t h ( words c o n t e n t )
     putStrLn ( show numWords ++ ” ” ++ p a t h )

  main = do
    a r g s <− getArgs
   mapM countWords a r g s
New notation!


   There was a lot to digest there. Let’s run through it all, from top
   to bottom.


   import System . E n v i r o n m e n t ( getArgs )

   “Import only the thing named getArgs from
   System.Environment.”
   Without an explicit (comma separated) list of names to import,
   everything that a module exports is imported into this one.
The do block




   Notice that this function’s body starts with the keyword do:

   countWords p a t h = do
     ...

   That keyword introduces a series of actions. Each action is
   somewhat similar to a statement in C or Python.
Executing an action and using its result



   The first line of our function’s body:

   countWords p a t h = do
     c o n t e n t <− r e a d F i l e p a t h

   This performs the action “readFile path”, and assigns the result
   to the name “content”.
   The special notation “<−” makes it clear that we are executing an
   action, i.e. not applying a pure function.
Applying a pure function



   We can use the let keyword inside a do block, and it applies a
   pure function, but the code that follows does not need to start
   with an in keyword.

      l e t numWords = l e n g t h ( words c o n t e n t )
      putStrLn ( show numWords ++ ” ” ++ p a t h )

   With both let and <−, the result is immutable as usual, and stays
   in scope until the end of the do block.
Executing an action




   This line executes an action, and ignores its return value:

      putStrLn ( show numWords ++ ”               ” ++ p a t h )
Compare and contrast

   Wonder how different imperative programming in Haskell is from
   other languages?


   def c o u n t w o r d s ( p a t h ) :
       c o n t e n t = open ( p a t h ) . r e a d ( )
       num words = l e n ( c o n t e n t . s p l i t ( ) )
       p r i n t r e p r ( num words ) + ” ” + p a t h


   countWords p a t h = do
       c o n t e n t <− r e a d F i l e p a t h
       l e t numWords = l e n g t h ( words c o n t e n t )
       putStrLn ( show numWords ++ ” ” ++ p a t h )
A few handy rules




   When you want to introduce a new name inside a do block:
       Use name <− action to perform an action and keep its result.
       Use let name = expression to evaluate a pure expression, and
       omit the in.
More adventures with ghci



   If we load our source file into ghci, we get an interesting type
   signature:

   *Main> :type countWords
   countWords :: FilePath -> IO ()


   See the result type of IO ()? That means “this is an action that
   performs I/O, and which returns nothing useful when it’s done.”
Main



  In Haskell, the entry point to an executable is named main. You
  are shocked by this, I am sure.

  main = do
    a r g s <− getArgs
   mapM countWords a r g s

  Instead of main being passed its command line arguments as in C,
  it uses the getArgs action to retrieve them.
What’s this mapM business?


  The map function can only call pure functions, so it has an
  equivalent named mapM that maps an impure action over a list of
  arguments and returns the list of results.
  The mapM function has a cousin, mapM , that throws away the
  result of each action it performs.
  In other words, this is one way to perform a loop over a list in
  Haskell.
  “mapM countWords args” means “apply countWords to every
  element of args in turn, and throw away each result.”
Compare and contrast II, electric boogaloo


   These don’t look as similar as their predecessors:

   def main ( ) :
       f o r name i n s y s . a r g v [ 1 : ] :
             c o u n t w o r d s ( name )


   main = do
       a r g s <− getArgs
       mapM countWords a r g s

   I wonder if we could change that.
Idiomatic word count in Python




   If we were writing “real” Python code, it would look more like this:

   def main ( ) :
       for path in s y s . argv [ 1 : ] :
            c = open ( p a t h ) . r e a d ( )
            p r i n t l e n ( c . s p l i t ( ) ) , path
Meet forM



  In the Control .Monad module, there are two functions named
  forM and forM . They are nothing more than mapM and mapM
  with their arguments flipped.

  In other words, these are identical:

  mapM countWords a r g s
  f o r M a r g s countWords

  That seems a bit gratuitous. Why should we care?
Function application as an operator


   In our last lecture, we were introduced to function composition:
   f . g =  x −> f ( g x )

   We can also write a function to apply a function:
   f $ x = f x

   This operator has a very low precedence, so we can use it to get
   rid of parentheses. Sometimes this makes code easier to read:
   putStrLn ( show numWords ++ ”               ” ++ p a t h )
   putStrLn $ show numWords ++ ”               ” ++ p a t h
Idiomatic word counting in Haskell


   See what’s different about this word counting?

   main = do
     a r g s <− getArgs
     f o r M a r g s $  a r g −> do
          c o n t e n t <− r e a d F i l e a r g
          l e t l e n = l e n g t h ( words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g )

   Doesn’t that use of forM look remarkably like a for loop in some
   other language? That’s because it is one.
The reason for the $




   Notice that the body of the forM loop is an anonymous function
   of one argument.
   We put the $ in there so that we wouldn’t have to either wrap the
   entire function body in parentheses, or split it out and give it a
   name.
The good




  Here’s our original code, using the $ operator:

     f o r M a r g s $  a r g −> do
          c o n t e n t <− r e a d F i l e a r g
          l e t l e n = l e n g t h ( words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g )
The bad




  If we omit the $, we could use parentheses:

     f o r M a r g s (  a r g −> do
          c o n t e n t <− r e a d F i l e a r g
          l e t l e n = l e n g t h ( words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g ) )
And the ugly


   Or we could give our loop body a name:

      l e t body a r g = do
           c o n t e n t <− r e a d F i l e a r g
           l e t l e n = l e n g t h ( words c o n t e n t )
          putStrLn ( show l e n ++ ” ” ++ a r g ) )
      f o r M a r g s body

   Giving such a trivial single-use function a name seems gratuitous.
   Nevertheless, it should be clear that all three pieces of code are
   identical in their operation.
Trying it out

   Let’s assume we’ve saved our source file as WC.hs, and give it a try:

   $ ghc --make WC
   [1 of 1] Compiling Main ( WC.hs, WC.o )
   Linking WC ...

   $ du -h ascii.txt
   58M ascii.txt

   $ time ./WC ascii.txt
   9873630 ascii.txt

   real 0m8.043s
Comparison shopping



   How does the performance of our WC program compare with the
   system’s built-in wc command?

   $ export LANG=C
   $ time wc -w ascii.txt
   9873630 ascii.txt

   real 0m0.447s

   Ouch! The C version is almost 18 times faster.
A second try



   Does it help if we recompile with optimisation?

   $ ghc -fforce-recomp -O --make WC
   $ time ./WC ascii.txt
   9873630 ascii.txt

   real 0m7.696s

   So that made our code 5% faster. Ugh.
What’s going on here?



   Remember that in Haskell, a string is a list. And a list is
   represented as a linked list.
   This means that every character gets its own list element, and list
   elements are not allocated contiguously. For large data structures,
   list overhead is negligible, but for characters, it’s a total killer.
   So what’s to be done?
   Enter the bytestring.
The original code




   main = do
     a r g s <− getArgs
     f o r M a r g s $  a r g −> do
          c o n t e n t <− r e a d F i l e a r g
          l e t l e n = l e n g t h ( words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g )
The bytestring code

   A bytestring is a contiguously-allocated array of bytes. Because
   there’s no pointer-chasing overhead, this should be faster.

   import q u a l i f i e d Data . B y t e S t r i n g . Char8 a s B

   main = do
     a r g s <− getArgs
     f o r M a r g s $  a r g −> do
          c o n t e n t <− B . r e a d F i l e a r g
          l e t l e n = l e n g t h (B . words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g )

   Notice the import qualified—this allows us to write B instead of
   Data.ByteString.Char8 wherever we want to use a name imported
   from that module.
So is it faster?

   How does this code perform?

   $ time ./WC ascii.txt
   9873630 ascii.txt

   real 0m8.043s

   $ time ./WC-BS ascii.txt
   9873630 ascii.txt

   real 0m1.434s


   Not bad! We’re 6x faster than the String code, and now just 3x
   slower than the C code.
Seriously? Bytes for text?




   There is, of course, a snag to using bytestrings: they’re strings of
   bytes, not characters.
   This is the 21st century, and everyone should be using Unicode
   now, right?
   Our answer to this problem in Haskell is to use a package named
   Data.Text.
Unicode-aware word count


   import q u a l i f i e d Data . Text a s T
   import Data . Text . E n c o d i n g ( d e c o d e U t f 8 )
   import q u a l i f i e d Data . B y t e S t r i n g . Char8 a s B

   main = do
     a r g s <− getArgs
     f o r M a r g s $  a r g −> do
          b y t e s <− B . r e a d F i l e a r g
          l e t content = decodeUtf8 bytes
                  l e n = l e n g t h (T . words c o n t e n t )
         putStrLn ( show l e n ++ ” ” ++ a r g )
What happens here?




  Notice that we still use bytestrings to read the initial data in.
  Now, however, we use decodeUtf8 to turn the raw bytes from
  UTF-8 into the Unicode representation that Data.Text uses
  internally.
  We then use Data.Text’s words function to split the big string into
  a list of words.
Comparing Unicode performance
   For comparison, let’s first try a Unicode-aware word count in C, on
   a file containing 112.6 million characters of UTF-8-encoded Greek:

   $ du -h greek.txt
   196M greek.txt

   $ export LANG=en_US.UTF-8
   $ time wc -w greek.txt
   16917959 greek.txt

   real 0m8.306s

   $ time ./WC-T greek.txt
   16917959 greek.txt

   real 0m7.350s
What did we just see?




   Wow! Our tiny Haskell program is actually 13% faster than the
   system’s wc command!
   This suggests that if we choose the right representation, we can
   write real-world code that is both brief and highly efficient.
   This ought to be immensely cheering.

More Related Content

PDF
Real World Haskell: Lecture 1
PDF
DEFUN 2008 - Real World Haskell
PDF
Real World Haskell: Lecture 6
PPT
BayFP: Concurrent and Multicore Haskell
PDF
Real World Haskell: Lecture 3
PDF
Real World Haskell: Lecture 2
PDF
Real World Haskell: Lecture 4
PDF
Real World Haskell: Lecture 5
Real World Haskell: Lecture 1
DEFUN 2008 - Real World Haskell
Real World Haskell: Lecture 6
BayFP: Concurrent and Multicore Haskell
Real World Haskell: Lecture 3
Real World Haskell: Lecture 2
Real World Haskell: Lecture 4
Real World Haskell: Lecture 5

What's hot (20)

PPTX
Regular expressions in Python
PDF
Scala 3 enum for a terser Option Monad Algebraic Data Type
PDF
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
PDF
The Functional Programming Triad of Map, Filter and Fold
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
PDF
Big picture of category theory in scala with deep dive into contravariant and...
PPT
Haskell retrospective
PPT
Introduction to Python - Part Two
PPT
Introduction to Python - Part Three
PDF
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
PDF
Haskell for data science
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
Python Programming - XI. String Manipulation and Regular Expressions
PPT
Adv. python regular expression by Rj
PPTX
A brief introduction to lisp language
Regular expressions in Python
Scala 3 enum for a terser Option Monad Algebraic Data Type
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
The Functional Programming Triad of Map, Filter and Fold
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Big picture of category theory in scala with deep dive into contravariant and...
Haskell retrospective
Introduction to Python - Part Two
Introduction to Python - Part Three
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Haskell for data science
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Python Programming - XI. String Manipulation and Regular Expressions
Adv. python regular expression by Rj
A brief introduction to lisp language
Ad

Viewers also liked (20)

PPT
香港六合彩身在富中
PPT
Opdracht Informatica
PPT
Increase Adwords Profits
PPT
PresentacióN1
 
PPT
Slide Share Thin2
PPT
Are We There Yet
PDF
Security Storage Containers
PPS
數位學院:好事吸引力
PPT
Pel1
PPT
Pp Msae A Deans
PPTX
The Power of Story and 5 Ways to Share it Visually
PPT
Unit 4
PDF
Hagelin Scientistsfor Peace
PPT
Toekomst van het leren
PPT
Encuesta
PPT
Pass Serie Spistol3 Revised
PDF
Pronk like you mean it
PPT
SHAC Resource Management Issues
PPT
Learning analytics MBO Onderwijs
PPT
Electives at TMS
香港六合彩身在富中
Opdracht Informatica
Increase Adwords Profits
PresentacióN1
 
Slide Share Thin2
Are We There Yet
Security Storage Containers
數位學院:好事吸引力
Pel1
Pp Msae A Deans
The Power of Story and 5 Ways to Share it Visually
Unit 4
Hagelin Scientistsfor Peace
Toekomst van het leren
Encuesta
Pass Serie Spistol3 Revised
Pronk like you mean it
SHAC Resource Management Issues
Learning analytics MBO Onderwijs
Electives at TMS
Ad

Similar to Real World Haskell: Lecture 7 (20)

ZIP
Haskell Jumpstart
PDF
Functional programming using haskell notes iitk
PDF
05. haskell streaming io
PDF
Cs hangman
PDF
Why is Haskell so hard! (And how to deal with it?)
PDF
High-Performance Haskell
PDF
The monad fear
PDF
Template Haskell
PDF
Streamly: Concurrent Data Flow Programming
PDF
Monad Fact #6
PPT
haskell5.ppt is a marketing document lol
PPTX
Introduction to fundamentaals of computing.pptx
PDF
Introduction to Functional Languages
PDF
Why Haskell Matters
PDF
The Ring programming language version 1.4 book - Part 11 of 30
PDF
01. haskell introduction
PDF
Making the most of lambdas
PPTX
Introduction to Haskell: 2011-04-13
Haskell Jumpstart
Functional programming using haskell notes iitk
05. haskell streaming io
Cs hangman
Why is Haskell so hard! (And how to deal with it?)
High-Performance Haskell
The monad fear
Template Haskell
Streamly: Concurrent Data Flow Programming
Monad Fact #6
haskell5.ppt is a marketing document lol
Introduction to fundamentaals of computing.pptx
Introduction to Functional Languages
Why Haskell Matters
The Ring programming language version 1.4 book - Part 11 of 30
01. haskell introduction
Making the most of lambdas
Introduction to Haskell: 2011-04-13

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Cell Structure & Organelles in detailed.
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Insiders guide to clinical Medicine.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
RMMM.pdf make it easy to upload and study
Supply Chain Operations Speaking Notes -ICLT Program
Cell Structure & Organelles in detailed.
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Anesthesia in Laparoscopic Surgery in India
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
TR - Agricultural Crops Production NC III.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Insiders guide to clinical Medicine.pdf
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Basic Mud Logging Guide for educational purpose
RMMM.pdf make it easy to upload and study

Real World Haskell: Lecture 7

  • 1. Real World Haskell: Lecture 7 Bryan O’Sullivan 2009-12-09
  • 2. Getting things done It’s great to dwell so much on purity, but we’d like to maybe use Haskell for practical programming some time. This leaves us concerned with talking to the outside world.
  • 3. Word count import System . E n v i r o n m e n t ( getArgs ) import C o n t r o l . Monad ( f o r M ) countWords p a t h = do c o n t e n t <− r e a d F i l e p a t h l e t numWords = l e n g t h ( words c o n t e n t ) putStrLn ( show numWords ++ ” ” ++ p a t h ) main = do a r g s <− getArgs mapM countWords a r g s
  • 4. New notation! There was a lot to digest there. Let’s run through it all, from top to bottom. import System . E n v i r o n m e n t ( getArgs ) “Import only the thing named getArgs from System.Environment.” Without an explicit (comma separated) list of names to import, everything that a module exports is imported into this one.
  • 5. The do block Notice that this function’s body starts with the keyword do: countWords p a t h = do ... That keyword introduces a series of actions. Each action is somewhat similar to a statement in C or Python.
  • 6. Executing an action and using its result The first line of our function’s body: countWords p a t h = do c o n t e n t <− r e a d F i l e p a t h This performs the action “readFile path”, and assigns the result to the name “content”. The special notation “<−” makes it clear that we are executing an action, i.e. not applying a pure function.
  • 7. Applying a pure function We can use the let keyword inside a do block, and it applies a pure function, but the code that follows does not need to start with an in keyword. l e t numWords = l e n g t h ( words c o n t e n t ) putStrLn ( show numWords ++ ” ” ++ p a t h ) With both let and <−, the result is immutable as usual, and stays in scope until the end of the do block.
  • 8. Executing an action This line executes an action, and ignores its return value: putStrLn ( show numWords ++ ” ” ++ p a t h )
  • 9. Compare and contrast Wonder how different imperative programming in Haskell is from other languages? def c o u n t w o r d s ( p a t h ) : c o n t e n t = open ( p a t h ) . r e a d ( ) num words = l e n ( c o n t e n t . s p l i t ( ) ) p r i n t r e p r ( num words ) + ” ” + p a t h countWords p a t h = do c o n t e n t <− r e a d F i l e p a t h l e t numWords = l e n g t h ( words c o n t e n t ) putStrLn ( show numWords ++ ” ” ++ p a t h )
  • 10. A few handy rules When you want to introduce a new name inside a do block: Use name <− action to perform an action and keep its result. Use let name = expression to evaluate a pure expression, and omit the in.
  • 11. More adventures with ghci If we load our source file into ghci, we get an interesting type signature: *Main> :type countWords countWords :: FilePath -> IO () See the result type of IO ()? That means “this is an action that performs I/O, and which returns nothing useful when it’s done.”
  • 12. Main In Haskell, the entry point to an executable is named main. You are shocked by this, I am sure. main = do a r g s <− getArgs mapM countWords a r g s Instead of main being passed its command line arguments as in C, it uses the getArgs action to retrieve them.
  • 13. What’s this mapM business? The map function can only call pure functions, so it has an equivalent named mapM that maps an impure action over a list of arguments and returns the list of results. The mapM function has a cousin, mapM , that throws away the result of each action it performs. In other words, this is one way to perform a loop over a list in Haskell. “mapM countWords args” means “apply countWords to every element of args in turn, and throw away each result.”
  • 14. Compare and contrast II, electric boogaloo These don’t look as similar as their predecessors: def main ( ) : f o r name i n s y s . a r g v [ 1 : ] : c o u n t w o r d s ( name ) main = do a r g s <− getArgs mapM countWords a r g s I wonder if we could change that.
  • 15. Idiomatic word count in Python If we were writing “real” Python code, it would look more like this: def main ( ) : for path in s y s . argv [ 1 : ] : c = open ( p a t h ) . r e a d ( ) p r i n t l e n ( c . s p l i t ( ) ) , path
  • 16. Meet forM In the Control .Monad module, there are two functions named forM and forM . They are nothing more than mapM and mapM with their arguments flipped. In other words, these are identical: mapM countWords a r g s f o r M a r g s countWords That seems a bit gratuitous. Why should we care?
  • 17. Function application as an operator In our last lecture, we were introduced to function composition: f . g = x −> f ( g x ) We can also write a function to apply a function: f $ x = f x This operator has a very low precedence, so we can use it to get rid of parentheses. Sometimes this makes code easier to read: putStrLn ( show numWords ++ ” ” ++ p a t h ) putStrLn $ show numWords ++ ” ” ++ p a t h
  • 18. Idiomatic word counting in Haskell See what’s different about this word counting? main = do a r g s <− getArgs f o r M a r g s $ a r g −> do c o n t e n t <− r e a d F i l e a r g l e t l e n = l e n g t h ( words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g ) Doesn’t that use of forM look remarkably like a for loop in some other language? That’s because it is one.
  • 19. The reason for the $ Notice that the body of the forM loop is an anonymous function of one argument. We put the $ in there so that we wouldn’t have to either wrap the entire function body in parentheses, or split it out and give it a name.
  • 20. The good Here’s our original code, using the $ operator: f o r M a r g s $ a r g −> do c o n t e n t <− r e a d F i l e a r g l e t l e n = l e n g t h ( words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g )
  • 21. The bad If we omit the $, we could use parentheses: f o r M a r g s ( a r g −> do c o n t e n t <− r e a d F i l e a r g l e t l e n = l e n g t h ( words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g ) )
  • 22. And the ugly Or we could give our loop body a name: l e t body a r g = do c o n t e n t <− r e a d F i l e a r g l e t l e n = l e n g t h ( words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g ) ) f o r M a r g s body Giving such a trivial single-use function a name seems gratuitous. Nevertheless, it should be clear that all three pieces of code are identical in their operation.
  • 23. Trying it out Let’s assume we’ve saved our source file as WC.hs, and give it a try: $ ghc --make WC [1 of 1] Compiling Main ( WC.hs, WC.o ) Linking WC ... $ du -h ascii.txt 58M ascii.txt $ time ./WC ascii.txt 9873630 ascii.txt real 0m8.043s
  • 24. Comparison shopping How does the performance of our WC program compare with the system’s built-in wc command? $ export LANG=C $ time wc -w ascii.txt 9873630 ascii.txt real 0m0.447s Ouch! The C version is almost 18 times faster.
  • 25. A second try Does it help if we recompile with optimisation? $ ghc -fforce-recomp -O --make WC $ time ./WC ascii.txt 9873630 ascii.txt real 0m7.696s So that made our code 5% faster. Ugh.
  • 26. What’s going on here? Remember that in Haskell, a string is a list. And a list is represented as a linked list. This means that every character gets its own list element, and list elements are not allocated contiguously. For large data structures, list overhead is negligible, but for characters, it’s a total killer. So what’s to be done? Enter the bytestring.
  • 27. The original code main = do a r g s <− getArgs f o r M a r g s $ a r g −> do c o n t e n t <− r e a d F i l e a r g l e t l e n = l e n g t h ( words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g )
  • 28. The bytestring code A bytestring is a contiguously-allocated array of bytes. Because there’s no pointer-chasing overhead, this should be faster. import q u a l i f i e d Data . B y t e S t r i n g . Char8 a s B main = do a r g s <− getArgs f o r M a r g s $ a r g −> do c o n t e n t <− B . r e a d F i l e a r g l e t l e n = l e n g t h (B . words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g ) Notice the import qualified—this allows us to write B instead of Data.ByteString.Char8 wherever we want to use a name imported from that module.
  • 29. So is it faster? How does this code perform? $ time ./WC ascii.txt 9873630 ascii.txt real 0m8.043s $ time ./WC-BS ascii.txt 9873630 ascii.txt real 0m1.434s Not bad! We’re 6x faster than the String code, and now just 3x slower than the C code.
  • 30. Seriously? Bytes for text? There is, of course, a snag to using bytestrings: they’re strings of bytes, not characters. This is the 21st century, and everyone should be using Unicode now, right? Our answer to this problem in Haskell is to use a package named Data.Text.
  • 31. Unicode-aware word count import q u a l i f i e d Data . Text a s T import Data . Text . E n c o d i n g ( d e c o d e U t f 8 ) import q u a l i f i e d Data . B y t e S t r i n g . Char8 a s B main = do a r g s <− getArgs f o r M a r g s $ a r g −> do b y t e s <− B . r e a d F i l e a r g l e t content = decodeUtf8 bytes l e n = l e n g t h (T . words c o n t e n t ) putStrLn ( show l e n ++ ” ” ++ a r g )
  • 32. What happens here? Notice that we still use bytestrings to read the initial data in. Now, however, we use decodeUtf8 to turn the raw bytes from UTF-8 into the Unicode representation that Data.Text uses internally. We then use Data.Text’s words function to split the big string into a list of words.
  • 33. Comparing Unicode performance For comparison, let’s first try a Unicode-aware word count in C, on a file containing 112.6 million characters of UTF-8-encoded Greek: $ du -h greek.txt 196M greek.txt $ export LANG=en_US.UTF-8 $ time wc -w greek.txt 16917959 greek.txt real 0m8.306s $ time ./WC-T greek.txt 16917959 greek.txt real 0m7.350s
  • 34. What did we just see? Wow! Our tiny Haskell program is actually 13% faster than the system’s wc command! This suggests that if we choose the right representation, we can write real-world code that is both brief and highly efficient. This ought to be immensely cheering.