Re:Implement with types, not your brain (2019)
by Jtsummers on Tuesday February 25, 2020 @02:14PM
(#22416252)
f :: a -> a
can only be satisfied by the function identity because there are no constraints on the type (a). identity is the lowest common denominator function that can transform an object of any type to another object of the same type.If you added a constraint on a, for instance:
f :: Num a => a -> a
Now f can be almost any function which can transform a numeric type back to the same numeric type. [0] describes class Num. So f, with this constraint, can now be negate, abs, signum, or something which combined the first parameter with itself using one of the operators, and so on.By removing constraints on the type itself, Haskell necessarily restricts the set of operations that can be performed.
[0] https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelu...
Re:Implement with types, not your brain (2019)
by SaidinWoT on Tuesday February 25, 2020 @01:10PM
(#22415537)
The key point making `a -> a` have only a single implementation is that the type `a` is a wildcard that's determined by the caller - it must be possible for the implementation to accept any value of any type. The identity function is the only thing that can do that for all possible values.
If the type were `Int -> Int`, it could do a lot more.
Re:Implement with types, not your brain (2019)
by bweitzman on Tuesday February 25, 2020 @01:13PM
(#22415571)
changing a record requires a more specific type than `forall a. a`
the type `forall a . a -> a` does truly have one single (non exception throwing) implementation since there is no information you can glean about your argument other than the fact that it exists.
Once you have more structure, for example in `Person -> Person` or even `forall a . [a] -> [a]`, you have more possible implementations than just the identity function.
Even there, it's not true, right? It's been a while since I learned / used Haskell, but I think something that transforms a { name: 'bob' } to a { name: 'sally' } would fit that bill, right? So, there are many implementations which meet the type signature, but you'd be pretty surprised if your `identity` function did this.