In Functional Programming, what is a functor?

后端 未结 17 711
孤独总比滥情好
孤独总比滥情好 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:53

    There is a pretty good example in the O'Reilly OCaml book that's on Inria's website (which as of writing this is unfortunately down). I found a very similar example in this book used by caltech: Introduction to OCaml (pdf link). The relevant section is the chapter on functors (Page 139 in the book, page 149 in the PDF).

    In the book they have a functor called MakeSet which creates a data structure that consists of a list, and functions to add an element, determine if an element is in the list, and to find the element. The comparison function that is used to determine if it's in/not in the set has been parametrized (which is what makes MakeSet a functor instead of a module).

    They also have a module that implements the comparison function so that it does a case insensitive string compare.

    Using the functor and the module that implements the comparison they can create a new module in one line:

    module SSet = MakeSet(StringCaseEqual);;
    

    that creates a module for a set data structure that uses case insensitive comparisons. If you wanted to create a set that used case sensitive comparisons then you would just need to implement a new comparison module instead of a new data structure module.

    Tobu compared functors to templates in C++ which I think is quite apt.

提交回复
热议问题