Skip to content

Commit a17788e

Browse files
committed
Improves hkt docs
1 parent ecc2aea commit a17788e

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

docs/pages/hkt.rst

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,71 @@ Later you will learn how to
246246
:ref:`create your own types <create-your-own-container>` that support kinds!
247247

248248

249+
FAQ
250+
---
251+
252+
Which types you can use with KindN?
253+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
254+
255+
The first position in all ``KindN`` types
256+
can be occupied by either ``Instance`` type or ``TypeVar`` with ``bound=``.
257+
258+
Let's see an example:
259+
260+
.. code:: python
261+
262+
>>> from typing import TypeVar
263+
>>> from returns.primitives.hkt import KindN, kinded
264+
>>> from returns.interfaces.mappable import MappableN
265+
266+
>>> _FirstType = TypeVar('_FirstType')
267+
>>> _SecondType = TypeVar('_SecondType')
268+
>>> _ThirdType = TypeVar('_ThirdType')
269+
>>> _MappableKind = TypeVar('_MappableKind', bound=MappableN)
270+
271+
>>> @kinded
272+
... def works_with_interface(
273+
... container: KindN[_MappableKind, _FirstType, _SecondType, _ThirdType],
274+
... ) -> KindN[_MappableKind, str, _SecondType, _ThirdType]:
275+
... return container.map(str)
276+
277+
This version of ``works_with_interface`` will work
278+
with any subtype of ``MappableN``.
279+
Because we use ``_MappableKind`` in its definition.
280+
And ``_MappableKind`` is a ``TypeVar`` bound to ``MappableN``.
281+
Arguments of non ``MappableN`` subtypes will be rejected by a type-checker:
282+
283+
.. code:: python
284+
285+
>>> from returns.maybe import Maybe
286+
>>> from returns.io import IO
287+
>>> from returns.result import Success
288+
289+
>>> assert works_with_interface(Maybe.from_value(1)) == Maybe.from_value('1')
290+
>>> assert works_with_interface(IO.from_value(1)) == IO.from_value('1')
291+
>>> assert works_with_interface(Success(1)) == Success('1')
292+
293+
In contrast, we can work directly with some specific type,
294+
let's say ``Maybe`` container:
295+
296+
.. code:: python
297+
298+
>>> from returns.maybe import Maybe
299+
300+
>>> @kinded
301+
... def works_with_maybe(
302+
... container: KindN[Maybe, _FirstType, _SecondType, _ThirdType],
303+
... ) -> KindN[Maybe, str, _SecondType, _ThirdType]:
304+
... return container.map(str)
305+
306+
>>> assert works_with_maybe(Maybe.from_value(1)) == Maybe.from_value('1')
307+
308+
Function ``works_with_maybe`` will work correctly with ``Maybe`` instance.
309+
Other types will be rejected.
310+
311+
So, choose wisely which mechanism you need.
312+
313+
249314
API Reference
250315
-------------
251316

0 commit comments

Comments
 (0)