Most functional programming languages (e.g. Common Lisp, Scheme / Racket, Clojure, Haskell, Scala, Ocaml, SML) support some common higher-order functions on lists, such as map
, filter
, takeWhile
, dropWhile
, foldl
, foldr
(see e.g. Common Lisp, Scheme / Racket, Clojure side-by-side reference sheet, the Haskell, Scala, OCaml, and the SML documentation.)
Does C++11 have equivalent standard methods or functions on lists? For example, consider the following Haskell snippet:
let xs = [1, 2, 3, 4, 5]
let ys = map (\x -> x * x) xs
How can I express the second expression in modern standard C++?
std::list<int> xs = ... // Initialize the list in some way.
std::list<int> ys = ??? // How to translate the Haskell expression?
What about the other higher-order functions mentioned above?
Can they be directly expressed in C++?
Data.Sequence
in Haskell? It's comparatively ugly.[a]
. You either have to hide the prelude function, hack around prelude, or choose a different and less intuitive name.Functor
,Foldable
, andTraversable
achieve this in as abstract a way as I can think.Data.Sequence
is an instance of all of these, so you can just dofmap (\x -> x * x) xs
.map
isfmap
specialized for beginners.