Haskell: example of function of type a -> a, besides the identity

后端 未结 5 1907
情书的邮戳
情书的邮戳 2020-12-14 08:03

I\'ve just started playing a little with Haskell... I want to write a function of the same type of the identity. Obviously, not equivalent to it. That would be something lik

5条回答
  •  青春惊慌失措
    2020-12-14 08:18

    The key here is to understand that we know nothing about a, especially we have no way to generate a new one or to transform it to something different. Hence we have no choice as returning it (or the bottom value). As soon as we have more information about a (e.g. a context bound), we can do more interesting things with it:

    f :: Monoid a => a -> a
    f _ = mempty
    

    or

    f :: Monoid a => a -> a
    f x = x `mappend` x `mappend` x
    

    Or if you have the choice like in f :: (a, a) -> a, you have two possible implementations (ignoring the bottom values again), but for f :: (a, b) -> a you are back to one implementation, which is the same as for fst: While it is valid to call f with a pair of identical types, e.g. f ("x", "y"), you can be sure that f behaves like fst, because in the implementation of f you have no way to test if both argument types might be the same. Similarly, there is only one non-bottom version of f :: (a -> b) -> a -> b.

    Polymorphism limits the degrees of freedom, because you don't know anything about your arguments, and in some cases it boils down to one non-bottom version.

提交回复
热议问题