0

Higher order function map Definition:

map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x:map f xs

Then how to write a revmap function with pattern matching/ using function composition?

Sibi
  • 47,472
  • 16
  • 95
  • 163
Panini
  • 91
  • 6
  • You are doing pattern matching in the above example. – Sibi Jan 09 '14 at 05:52
  • 1
    What do you mean by `revmap`? Just `map` in the reverse order of the list? If that is your intention, you could just do `map f . reverse` – bheklilr Jan 09 '14 at 05:52
  • OP, bheklilr gave you one answer - but you really have to tell us what `revmap` means. :-) – S.R.I Jan 09 '14 at 06:30
  • If you have performance concerns about `map f . reverse` needing to traverse the list twice – GHC is pretty good at optimising this kind of overhead away. If performance is really crucial, you shouldn't be using lists anyway but e.g. `Data.Vector`. – leftaroundabout Jan 09 '14 at 11:26

1 Answers1

1

Assuming you want something like OCaml's rev_map function:

revmap :: (a -> b) -> [a] -> [b]
revmap f xs = go xs []
  where
    go [] acc     = acc
    go (x:xs) acc = go xs (f x : acc)
fjh
  • 12,121
  • 4
  • 46
  • 46