Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Haskell Design Patterns

You're reading from   Haskell Design Patterns Take your Haskell and functional programming skills to the next level by exploring new idioms and design patterns

Arrow left icon
Product type Paperback
Published in Nov 2015
Publisher
ISBN-13 9781783988723
Length 166 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ryan Lemmer Ryan Lemmer
Author Profile Icon Ryan Lemmer
Ryan Lemmer
Arrow right icon
View More author details
Toc

Higher-order functions

Functions are our first kind of "glue" in Haskell.

Functions as first-class citizens

Haskell functions are first-class citizens of the language. This means that:

  • We can name a function just as we can name any primitive value:
    square = \x -> x * x
  • We can pass functions to other functions:
    map square [1, 3, 5, 7]

    (Here, map is a higher-order function.)

  • Functions can produce other functions (here, by currying the foldr function):
    sum = foldr (+) 0
  • Functions can form part of other data structures:
    let fs = [(* 2), (* 3), (* 5)]
    zipWith (\f v -> f v) fs [1, 3, 5]

This places Haskell functions on an equal footing with primitive types.

Composing functions

Let's compose these three functions, f, g, and h, in a few different ways:

f, g, h :: String -> String

The most rudimentary way of combining them is through nesting:

z x = f (g (h x))

Function composition gives us a more idiomatic way of combining functions:

z' x = (f . g . h) x

Finally, we can abandon any reference to arguments:

z'' = f . g . h

This leaves us with an expression consisting of only functions. This is the "point-free" form.

Programming with functions in this style, free of arguments, is called tacit programming.

It is hard to argue against the elegance of this style, but in practice, point-free style can be more fun to write than to read: it can become difficult to infer types (and, therefore, meaning). Use this style when ease of reading is not overly compromised.

You have been reading a chapter from
Haskell Design Patterns
Published in: Nov 2015
Publisher:
ISBN-13: 9781783988723
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image