@@ -58,8 +58,53 @@ To use typeclasses you should understand these steps:
58
58
F2 --> F2
59
59
F2 --> F3["Calling"]
60
60
61
- # TODO: cover each steps
62
- # TODO: json example for simple types
61
+ Let's walk through this process step by step.
62
+ The first on is "Typeclass definition", where we create a new typeclass:
63
+
64
+ .. code :: python
65
+
66
+ >> > from classes import typeclass
67
+ >> > @ typeclass
68
+ ... def json (instance ) -> str :
69
+ ... """ That's definition!"""
70
+ ...
71
+
72
+ When typeclass is defined it only has a name and a signature
73
+ that all instances will share.
74
+ Let's define some instances:
75
+
76
+ .. code :: python
77
+
78
+ >> > @ json.instance(str )
79
+ ... def _json_str (instance : str ) -> str :
80
+ ... return ' "{0} "' .format(instance)
81
+ ...
82
+ >> > @ json.instance(int )
83
+ ... @ json.instance(float )
84
+ ... def _json_int_float (instance ) -> str :
85
+ ... return str (instance)
86
+ ...
87
+
88
+ That's how we define instances for our typeclass.
89
+ These instances will be executed when the corresponding type will be supplied.
90
+
91
+ And the last step is to call our typeclass
92
+ with different value of different types:
93
+
94
+ .. code :: python
95
+
96
+ >> > json(' text' )
97
+ ' "text"'
98
+ >> > json(1 )
99
+ ' 1'
100
+ >> > json(1.5 )
101
+ ' 1.5'
102
+
103
+ That's it. There's nothing extra about typeclasses. They can be:
104
+
105
+ - defined
106
+ - extended by new instances
107
+ - and called
63
108
64
109
65
110
singledispatch
@@ -68,3 +113,6 @@ singledispatch
68
113
One may ask, what is the difference
69
114
with `singledispatch <https://docs.python.org/3/library/functools.html#functools.singledispatch >`_
70
115
function from the standard library?
116
+
117
+ The thing about ``singledispatch `` is that it allows almost the same features.
118
+ But, it lacks type-safety. For example,
0 commit comments