Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal equivalent to algebraic data types

Tags:

crystal-lang

What is the idiomatic way to write the equivalent of an algebraic data type in Crystal? E.g. In Haskell I might have

data Stage = StageInitial String | StageFinished String

So I want to have two stages, each which has a string payload. Later on I want to pattern match on the stage.

How would you write this in Crystal?

like image 708
Sebastian Avatar asked Feb 27 '18 00:02

Sebastian


People also ask

Why are algebraic data types useful?

Just as algebra is fundamental to the whole of mathematics, algebraic data types (ADTs) are fundamental to many common functional programming languages. They're the primitives upon which all of our richer data structures are built, including everything from sets, maps, and queues, to bloom filters and neural networks.

What are sum types programming?

In computer science, a sum type, is a data structure used to hold a value that could take on several different, but fixed, types. In practical terms, a Sum Type can be thought of as an enum, with a payload (where that payload is data).

What is Crystal equivalent circuit?

Crystal Equivalent Circuit – The output frequency of oscillator circuits is normally not as stable as required for a great many applications. The component values all have tolerances, so that the actual oscillating frequency may easily be 10% higher or lower than the desired frequency.

What is an equivalence of categories in math?

In category theory, a branch of abstract mathematics, an equivalence of categories is a relation between two categories that establishes that these categories are "essentially the same". There are numerous examples of categorical equivalences from many areas of mathematics.

What is the Q factor of a crystal equivalent circuit?

Because the resistive component of the crystal equivalent circuit is relatively small, crystals have very large Q factors. Crystal Q factors range approximately from 2000 to 100 000, compared to a maximum of about 400 for an actual LC circuit. Resonance frequencies of available crystals are typically 10 kHz to 200 MHz.

What are the advantages of piezoelectric crystals in circuit design?

A well-designed circuit (of any type) normally uses as little power as possible to avoid component heating and to reduce the power supply load. Oscillator frequency stability can be dramatically improved by the use of piezoelectric crystals.


1 Answers

You can roughly emulate it with

record StageInitial, data : String
record StageFinished, data : String
alias Stage = StageInitial | StageFinished

then pattern match with case.

like image 178
Stephie Avatar answered Sep 22 '22 03:09

Stephie