4 ms·
> type classes are different because type classes are solved at compile time data Nested a = Nest a (Nested [a]) | Done deriving Show build :: Int ->
by Tarean 9y ago
> type classes are different because type classes are solved at compile time
data Nested a = Nest a (Nested [a]) | Done deriving Show
build :: Int -> a -> Nested a
build 0 a = Done
build i a = Nest a $ build (i- 1) [a]
main = do
i <- readLn
print (build i i)
if you build a value of Nested at runtime then it is impossible to do static dispatch and the dictionary has to be constructed at runtime as well.
Sorry that I mistyped the example at first. If you run this version:
> main
23
Nest 23 (Nest [23] (Nest [[23]] (Nest [[[23]]] (Nest [[[[23]]]] (Nest [[[[[23]]]]] (Nest [[[[[[23]]]]]] (Nest [[[[[[[23]]]]]]] (Nest [[[[[[[[23]]]]]]]] (Nest [[[[[[[[[23]]]]]]]]] (Nest [[[[[[[[[[23]]]]]]]]]] (Nest [[[[[[[[[[[23]]]]]]]]]]] (Nest [[[[[[[[[[[[23]]]]]]]]]]]] (Nest [[[[[[[[[[[[[23]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[23]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[23]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]]]]]] (Nest [[[[[[[[[[[[[[[[[[[[[[23]]]]]]]]]]]]]]]]]]]]]] Done))))))))))))))))))))))
The innermost Nested has type `Nest [[[[[[[[[[[[[[[[[[[[[[Int]]]]]]]]]]]]]]]]]]]]]]` which wasn't known at compile time so the show instance has to be constructed at runtime. This is called polymorphic recursion.
- deleted 9y ago[deleted]
- rocqua 9y agoTechnically, one might argue that i doesn't store a vtable, but only a reference to a type, which stores a vtable determined at runtime. I'd say the difference is minor to non-existent.
- bad_user 9y ago"i" does not store a reference to a type. Values in Haskell aren't tagged with their type like in OOP. There is no "isInstanceOf" check in Haskell.
- tromp 9y agoThis is a single Show instance that pattern matches to decide on whether to recurse, same as how lists are shown.
- Tarean 9y agoYeah, sorry, forgot the type variable at first.
- deleted 9y ago[deleted]