class Functor

home1 home2
 Bib
 Algorithms
 Bioinfo
 FP
 Logic
 MML
 Prog.Lang
and the
 Book

FP
 Haskell
  Haskell98
   Type Classes
    Functor
    Monad
    Kernels
    ?Function?
    ?Pair?
    Functor
class Functor f where               -- RR s.8.1 p.109
  fmap :: (a -> b) -> f a -> f b

instance Functor [] where           -- RR s.8.1 p.113
  fmap = map   -- i.e. the traditional Lisp map ...
  -- map g []     = []
  -- map g (x:xs) = (g x):(map g xs)

For example, declare a binary-tree type and make it an instance of class Functor:


module Main where

data Tree e = Fork e (Tree e) (Tree e) | EmptyTree deriving (Show)

instance Functor Tree where
  fmap f EmptyTree    = EmptyTree
  fmap f (Fork e l r) = Fork (f e) (fmap f l) (fmap f r)      --say

-- ----------------------------------------------------------------
l1 = ["anna", "bill", "carol"]                           --[String]
t1 = Fork "bill" (Fork "anna"  EmptyTree EmptyTree)   --Tree String
                 (Fork "carol" EmptyTree EmptyTree)
a2A 'a' = 'A'                                        --Char -> Char
a2A ch  = ch  --otherwise
g = map a2A                                      --String -> String

main =
    putStrLn(show(fmap g l1))                 --[String];      f=[]
 >> putStrLn(show(fmap g t1))                 --Tree String; f=Tree
 >> fmap g (readFile "abc.txt") >>= putStrLn  --IO String;     f=IO
-- ---------------------------------------------------LA--11/2005--

file abc.txt:
anna bill carol

Note that the one operator/program 'g' is applied to a [String] (list of String), a Tree (of) String, and an IO String (RR s.8.1 pp.111).  fmap defines what happens to a Functor instance -- to a "structure". g defines what happens to an element.

RR = revised report, CUP, 2003.
Coding Ockham's Razor, L. Allison, Springer

A Practical Introduction to Denotational Semantics, L. Allison, CUP

Linux
 Ubuntu
free op. sys.
OpenOffice
free office suite
The GIMP
~ free photoshop
Firefox
web browser

Haskell:
(:) cons
[x1,...] list
[ ]list
(++) append
\ λ :-)
:: has type

© L. Allison   http://www.allisons.org/ll/   (or as otherwise indicated),
Faculty of Information Technology (Clayton), Monash University, Australia 3800 (6/'05 was School of Computer Science and Software Engineering, Fac. Info. Tech., Monash University,
was Department of Computer Science, Fac. Comp. & Info. Tech., '89 was Department of Computer Science, Fac. Sci., '68-'71 was Department of Information Science, Fac. Sci.)
Created with "vi (Linux + Solaris)",  charset=iso-8859-1,  fetched Thursday, 28-Mar-2024 22:23:42 AEDT.