[Haskell-cafe] Structural typing of records in Haskell?
John Lato
jwlato at gmail.com
Mon Jan 13 09:05:04 UTC 2014
On Sun, Jan 12, 2014 at 5:00 PM, Cary Cherng <ccherng at gmail.com> wrote:
> Are there statically typed languages that treat records with
> structural typing, either imperative or functional?
>
OCaml uses structural typing for objects, and it's statically typed.
>
> Why should records not be structurally typed in Haskell? From what I
> understand, in the below foo cannot take a Rec2 even though Rec1 and
> Rec2 are essentially the same.
>
> data Rec1 = Rec1 { a :: Int, b :: Bool}
> data Rec2 = Rec2 { a :: Int, b :: Bool}
> foo :: Rec1 -> Bool
>
> Rec1 and Rec2 could be in totally different code libraries. I've read
> that preventing Rec2 being used in foo is good for the type safety in
> that Rec1 and Rec2 are likely intended to have semantically different
> meanings and allowing interchangeability breaks this.
>
> But then why is map structurally typed. map takes an argument of type
> a -> b and suppose some other higher order function bar also takes an
> argument of type a -> b. Should map instead have the below type which
> prevents a function of type a -> b semantically intended for bar from
> being accidentally used in map.
>
> newtype Mapper a b = Mapper { fn :: a -> b }
> map :: Mapper a b -> [a] -> [b]
> map _ [] = []
> map f (x:xs) = (fn f) x : map f xs
>
> If there is a mechanism that prevents something of type Rec2 from
> accidentally being used in foo, then why shouldn't there be something
> analogous that prevents something of type a -> b (meant for bar) from
> accidentally being used in map?
>
Because it's not possible to break anything by passing a total function to
map. Data structures can have internal invariants that functions meant for
structurally identical values will break. For example:
-- a natural number
> data Nat = Nat { unNat :: Int }
if we used structural typing, then ( 1-2 :: Nat ) would work, violating an
invariant that our custom API would preserve.
However, breaking code like this simply isn't possible with map. For
whatever 'a' type you're mapping over, a total function (a->b) will handle
it properly.
Or perhaps another way to think about it: map *cannot* care about the types
of the values it's operating over. It's the function's responsibility to
handle the input type appropriately, for whichever input it claims to take.
So long as the function is actually a function, map will do the right
thing.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140113/8b773716/attachment.html>
More information about the Haskell-Cafe
mailing list