oop - Achieving polymorphism in functional programming -
i'm enjoying transition object oriented language functional language. it's breath of fresh air, , i'm finding myself more productive before.
however - there 1 aspect of oop i've not yet seen satisfactory answer on fp side, , polymorphism. i.e. have large collection of data items, need processed in quite different ways when passed functions. sake of argument, let's there multiple factors driving polymorphic behaviour potentially exponentially many different behaviour combinations.
in oop can handled relatively using polymorphism: either through composition+inheritance or prototype-based approach.
in fp i'm bit stuck between:
- writing or composing pure functions implement polymorphic behaviours branching on value of each data item - feels rather assembling huge conditional or simulating virtual method table!
- putting functions inside pure data structures in prototype-like fashion - seems works doesn't violate idea of defining pure functions separately data?
what recommended functional approaches kind of situation? there other alternatives?
putting functions inside pure data structures in prototype-like fashion - seems works doesn't violate idea of defining pure functions separately data?
if virtual method dispatch way want approach problem, reasonable approach. separating functions data, distinctly non-functional notion begin with. consider fundamental principle of functional programming functions data. , feeling you're simulating virtual function, argue it's not simulation @ all. virtual function table, , that's ok.
just because language doesn't have oop support built in doesn't mean it's not reasonable apply same design principles - means you'll have write more of machinery other languages provide built-in, because you're fighting against natural spirit of language you're using. modern typed functional languages have deep support polymorphism, it's different approach polymorphism.
polymorphism in oop lot "existential quantification" in logic - polymorphic value has run-time type don't know is. in many functional programming languages, polymorphism more "universal quantification" - polymorphic value can instantiated compatible type user wants. they're 2 sides of exact same coin (in particular, swap places depending on whether you're looking @ function "inside" or "outside"), turns out extremely hard when designing language "make coin fair", in presence of other language features such subtyping or higher-kinded polymorphism (polymorphism on polymorphic types).
if helps, may want think of polymorphism in functional languages "generics" in c# or java, because that's type of polymorphism that, e.g., ml , haskell, favor.
Comments
Post a Comment