Achieving polymorphism in functional programming

后端 未结 5 1299
我寻月下人不归
我寻月下人不归 2020-12-07 10:52

I\'m currently enjoying the transition from an object oriented language to a functional language. It\'s a breath of fresh air, and I\'m finding myself much more productive t

5条回答
  •  庸人自扰
    2020-12-07 11:15

    Well, in Haskell you can always make a type-class to achieve a kind of polymorphism. Basically, it is defining functions that are processed for different types. Examples are the classes Eq and Show:

    data Foo = Bar | Baz
    
    instance Show Foo where
        show Bar = 'bar'
        show Baz = 'baz'
    
    main = putStrLn $ show Bar
    

    The function show :: (Show a) => a -> String is defined for every data type that instances the typeclass Show. The compiler finds the correct function for you, depending on the type.

    This allows to define functions more generally, for example:

    compare a b = a < b
    

    will work with any type of the typeclass Ord. This is not exactly like OOP, but you even may inherit typeclasses like so:

    class (Show a) => Combinator a where
        combine :: a -> a -> String
    

    It is up to the instance to define the actual function, you only define the type - similar to virtual functions.

    This is not complete, and as far as I know, many FP languages do not feature type classes. OCaml does not, it pushes that over to its OOP part. And Scheme does not have any types. But in Haskell it is a powerful way to achieve a kind of polymorphism, within limits.

    To go even further, newer extensions of the 2010 standard allow type families and suchlike.

    Hope this helped you a bit.

提交回复
热议问题