Search code examples
f#algebraalgebraic-data-types

Using algebraic data types for F# to solve algebra problems


How do algebraic data types in f# work? I want to see a basic sample program to explain it but can't seem to find any.

For example, maybe a code that does the quadratic formula or solutions to finding the areas of shapes.


Solution

  • The adjective algebraic in algebraic data types does not refer to a type used to solve an algebra problem, e.g.

    x + y = 3  or 5 * y = 10
    

    the adjective algebraic refers to the way types are constructed/declared using the algebraic operators of multiplication (*) and addition (+). In particular algebraic types can be product types (*) which are tuples, e.g.

    type Variable = string * int
    

    and sum types, which use the or character (|) instead of the plus character (+) which are discriminated unions, e.g.

    type Term =
        | Var of Variable
        | Const of Constant
        | App of Constant * Term list
    

    Once one understands that and shifts their thinking the Wikipedia article on algebraic data types should make sense and this will explain why you are not finding what you seek, e.g. articles that explain how to solve algebra problems using algebraic data types.

    In essence new types are built up from primitive data types such as int, char, string, etc. and the algebraic operators of product and summation but more importantly, algebraic data types are based on type theory and being a formal system bring with it all the benefits of a formal system.

    Also of note is the difference in the operators for declaring the tuple type and the operators used for creating a tuple value e.g.

    type Variable = string * int    type
    ("x",0)                         value
    

    notice the * operator for the type and the , operator for the value.

    Also

    type Term =                           type
      | Var of Variable
      | Const of Constant
      | App of Constant * Term list  
    
    Var("x",0)                            value
    Const("1")                            value
    App("add",[Const("1"),Var("x",0)])    value
    

    notice that each possible option has to have a case identifier when used with a value.

    As you learn more about ADTs you will run into generalized algebraic data type but sadly F# does not have them but have been requested.

    Mark Seemann provided a link to Power of mathematics - Reasoning about functional types by Tomas Petricek. Tomas then has a dead link fairly readable introduction but here it is or something similar: What the Heck are Algebraic Data Types? ( for Programmers ) or the series which I prefer by Chris Taylor which uses Haskell, but the ideas do translate to F#:

    The Algebra of Algebraic Data Types, Part 1
    The Algebra of Algebraic Data Types, Part 2
    The Algebra of Algebraic Data Types, Part 3