In Functional Programming, what is a functor?

后端 未结 17 708
孤独总比滥情好
孤独总比滥情好 2020-11-28 17:23

I\'ve come across the term \'Functor\' a few times while reading various articles on functional programming, but the authors typically assume the reader already understands

17条回答
  •  青春惊慌失措
    2020-11-28 17:44

    In OCaml, it's a parameterised module.

    If you know C++, think of an OCaml functor as a template. C++ only has class templates, and functors work at the module scale.

    An example of functor is Map.Make; module StringMap = Map.Make (String);; builds a map module that works with String-keyed maps.

    You couldn't achieve something like StringMap with just polymorphism; you need to make some assumptions on the keys. The String module contains the operations (comparison, etc) on a totally ordered string type, and the functor will link against the operations the String module contains. You could do something similar with object-oriented programming, but you'd have method indirection overhead.

提交回复
热议问题