Design a polymorphic API

I have a concept of scale that converts an input domain and an output range. However, there are several types of scales; each of them supports a subset of the possible operations and preserves a slightly different range.

For instance:

A ContinuousScale ( Scale (Float, Float) (Float, Float)), which has a domain (Float, Float), and the range (Float, Float)supports:

  • convert : Continuous -> Float -> Float convert a value from a domain to a range.
  • invert : Continuous -> Float -> Float converts a value from a range back to a domain.
  • domain : Continuous -> (Float, Float) return domain.
  • ticks : Continuous -> List Float returns values ​​suitable for drawing on an axis.

A mask Sequentialhas a scope (Float, Float)and function out Float -> a; it usually does not make much sense to store a range.

  • convert : Sequential a -> Float -> a converts a value from a domain to a range.
  • domain : Sequential a -> (Float, Float) return domain.
Scale

A Quantile (List Float) (List a). ; .

  • convert : Quantile a -> Float -> a .
  • invertExtent : Quantile a -> a -> (Float, Float) , .

, . , , , . , . "" , (.. identity) , . , .

API Elm?


, :

  • , , . .
  • , , / , . API . .
  • - Scale supportsOp1 supportsOp2 supportsOp3, SupportsOp Doesnt. , . op1 : Scale SupportsOp a b -> c. , . , .
  • ad hoc. , . . API - , .
+4
2

Scale a ?

type Scale a
  = Continuous (Float, Float) (Float, Float)
  | Sequential (Float, Float) (Float -> a)
  | Quantile (List Float) (Float -> a)

Sequential Quantile , Continuous - , . Continuous , ?

, case.

convert : Scale a -> Float -> a
convert scale val =
  case scale of
    Continuous domain range -> ...
    Sequential domain mapper -> ...
    Quantile domain mapper -> ...

, , Maybe a Nothing ? , , , Nothing, , .

invertExtent : Scale a -> a -> Maybe (Float, Float)
invertExtent scale val =
  case scale of
    Continuous _ _ -> Nothing
    Sequential _ _ -> Nothing
    Quantile domain mapper -> Just (...)
+3

, , .

, , , Maybe . , , , . , , -, Elm, , API.

Result, Maybe Task. , , (.. map andThen). , , .

, : , . , . , elm !


: , : https://gist.github.com/hkgumbs/069437f3e6b75ea15201b36188f6cc7a

+2

Source: https://habr.com/ru/post/1651682/


All Articles