Jump to content

Yet Another Haskell Tutorial/Language advanced/Solutions

From Wikibooks, open books for an open world
Haskell
Yet Another Haskell Tutorial
Preamble
Introduction
Getting Started
Language Basics (Solutions)
Type Basics (Solutions)
IO (Solutions)
Modules (Solutions)
Advanced Language (Solutions)
Advanced Types (Solutions)
Monads (Solutions)
Advanced IO
Recursion
Complexity

Sections and Infix Operators

[edit | edit source]

Local Declarations

[edit | edit source]

Partial Application

[edit | edit source]

Function func3 cannot be converted into point-free style. The others look something like:

func1 x = map (*x)

func2 f g = filter f . map g

func4 = map (+2) . filter (`elem` [1..10]) . (5:)

func5 = flip foldr 0 . flip . curry 

You might have been tempted to try to write func2 as filter f . map, trying to eta-reduce off the g. In this case, this isn't possible. This is because the function composition operator (.) has type (b -> c) -> (a -> b) -> (a -> c). In this case, we're trying to use map as the second argument. But map takes two arguments, while (.) expects a function which takes only one.


Pattern Matching

[edit | edit source]

Guards

[edit | edit source]

Instance Declarations

[edit | edit source]

The Eq Class

[edit | edit source]

The Show Class

[edit | edit source]

Other Important Classes

[edit | edit source]

The Ord Class

[edit | edit source]

The Enum Class

[edit | edit source]

The Num Class

[edit | edit source]

The Read Class

[edit | edit source]

Class Contexts

[edit | edit source]

Deriving Classes

[edit | edit source]

Datatypes Revisited

[edit | edit source]

Named Fields

[edit | edit source]

More Lists

[edit | edit source]

Standard List Functions

[edit | edit source]

List Comprehensions

[edit | edit source]

Arrays

[edit | edit source]

Finite Maps

[edit | edit source]

Layout

[edit | edit source]

The Final Word on Lists

[edit | edit source]

We can start out with a recursive definition:

and [] = True
and (x:xs) = x && and xs

From here, we can clearly rewrite this as:

and = foldr (&&) True

We can write this recursively as:

concatMap f [] = []
concatMap f (x:xs) = f x ++ concatMap f xs

This hints that we can write this as:

concatMap f = foldr (\a b -> f a ++ b) []

Now, we can do point elimination to get:

     foldr (\a b -> f a ++ b) []
==>  foldr (\a b -> (++) (f a) b) []
==>  foldr (\a -> (++) (f a)) []
==>  foldr (\a -> ((++) . f) a) []
==>  foldr ((++) . f) []