{"id":163,"date":"2023-04-14T11:59:19","date_gmt":"2023-04-14T10:59:19","guid":{"rendered":"https:\/\/blog.adonlon.org\/?p=163"},"modified":"2023-05-08T15:53:18","modified_gmt":"2023-05-08T14:53:18","slug":"fundamental-functional-types","status":"publish","type":"post","link":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/","title":{"rendered":"Fundamental Functional Types"},"content":{"rendered":"\n<p>Functional programming tries to use return types to convey information. This is particularly important when it comes to errors and failures. Procedural approaches have used exceptions, sentinel values, mutable parameters and return codes to convey &#8216;extra&#8217; information about the result of a call. However, not all of these are appropriate in a pure functional world. So we prefer types as the fundamental way of carrying knowledge through a program. Here I want to explore some of the fundamental functional types which form the building blocks of functional programming. Examples come from the Scala language. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Option<\/h3>\n\n\n\n<p>The first functional type to tackle is the <code>Option<\/code>. We use it as an alternative to the sentinel <code>null<\/code> value and the required null-checks and guards which are needed to use it correctly.<\/p>\n\n\n\n<p>An <code>Option[A]<\/code> is the functional way of representing a nullable value. It represents an object which might not have any value or might have a single value of type <code>A<\/code>. The procedural world has woken up to the <a href=\"https:\/\/www.infoq.com\/presentations\/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare\/\">problems<\/a> associated with the <code>null<\/code> value and <code>Option<\/code> is creeping into more object-oriented languages these days either in widely used libraries (e.g. Guava) or as part of the core language library itself (e.g. JDK8).<\/p>\n\n\n\n<p>The difficulty with <code>null<\/code> is primarily related to its type. <code>null<\/code> is not generally a valid value of the type of the variable and so accessing the variable through that type&#8217;s API when its value is <code>null<\/code> is an error. To operate effectively in a language with nullable variables you have to first discover whether the value is <code>null<\/code> and then act appropriately. There&#8217;s no way of telling whether a given variable <strong>is<\/strong> actually nullable or not. To work with them you have to make some reasonable assumptions or work on convention.<\/p>\n\n\n\n<p>Using <code>Option<\/code> can make it clear that the value in question <em>might<\/em> not represent a real value and <em>must<\/em> be validated before being treated as a pure value. The addition of a <code>map()<\/code> method in its API allows for accessing the value in a null-safe fashion. <code>map<\/code> takes a <code>f: A =&gt; B<\/code> and produces an <code>Option[B]<\/code> which is itself either <code>null<\/code> or the value of <code>f(a)<\/code>, where a is the contained value.<\/p>\n\n\n\n<p>In most functional languages (and, specifically, in Scala) there are exactly 2 subtypes of <code>Option[_]<\/code>, which can be valuable when matching. The first is <code>None<\/code> and the second is <code>Some[_]<\/code>. As might be expected, <code>None<\/code> is the null type and <code>Some[A]<\/code> represents a single value of type <code>A<\/code> which is <em>not<\/em> null.<\/p>\n\n\n\n<p>What <code>Option<\/code> actually does for us is to remove the need to be paranoid about null checking. It&#8217;s clear where something <em>might<\/em> be <code>null<\/code> and the only time that an explicit check is required is when we really need to collapse the <code>Option<\/code> down to a single value. Most functions operating on the underlying value can be passed into the <code>map()<\/code> method, or its friends, and so never have to do null checking.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">val x: Option[String] = None\nval y: Option[Int] = x.map(_.length)\ny match {\n  case None =&gt; println(\"(null) value\")\n  case _ =&gt; println(\"This never happens\")\n}\n\nval a: Option[String] = Some(\"some string\")\nval b: Option[Int] = a.map(_.length)\nb match {\n  case None =&gt; println(\"This never happens\")\n  case Some(length) =&gt; println(s\"Original string length = $length\")\n}<\/pre>\n\n\n\n<div class=\"wp-block-di-blocks-paragraph\" id=\"di-blocks-paragraph-77f13263-16de-4304-b96d-502ffed78401\"><div class=\"di-blocks-paragraph di-blocks-outer\"><p class=\"di-blocks-align-left di-blocks-paragraph-main\" data-animate=\"\">When the <code>Option<\/code> does need to be collapsed into a value there are methods which allow for managing the two-sided nature of the type. Where a &#8216;default&#8217; value can be provided a method such as <code>orElse<\/code> can be used. Where the default is challenging to generate a lazily evaluated <code>getOrElse<\/code> allows passing a method which will only be called when necessary.  <\/p><\/div><\/div>\n\n\n\n<p>Another way of thinking about <code>Option[A]<\/code> is as a collection which contains either 1 value or 0 values.<\/p>\n\n\n\n<p>Yet another way of thinking about <code>Option<\/code> is as a monad, and it does not disappoint there having both a <code>map(f: A =&gt; B)<\/code> as well as a <code>flatten()<\/code> method.<\/p>\n\n\n\n<p>The closed type hierarchy is characteristic of an algebraic data type and is a very useful technique in functional programming. In particular it works well with pattern matching.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Either<\/h3>\n\n\n\n<p>An <code>Either[A, B]<\/code> is a more general form of an <code>Option[A]<\/code>, and an <code>Option<\/code> can also be represented as <code>Either[None, A]<\/code>. It represents a single value which might be of type <code>A<\/code> or of type <code>B<\/code>. Conventionally, the two types are accessed independently as the <code>.left()<\/code> and <code>.right()<\/code> members respectively, which return a <code>LeftProjection[A]<\/code> or <code>RightProjection[B]<\/code>. The  two types are very like optional types and allow for independently mapping the values depending on what is contained within the  <code>Either[]<\/code>. This is particularly useful when only one of the values needs to be transformed.<\/p>\n\n\n\n<p>The <code>Either<\/code> type itself is modeled as an abstract data type with two subtypes &#8211; <code>Left[A]<\/code> and <code>Right[B]<\/code>. This gives the <code>Either<\/code> type the ability to engage in pattern matching.<\/p>\n\n\n\n<p><code>Either<\/code> is so close to <code>Option<\/code> that there are actually methods on the Scala implementations&#8217; APIs which allow for flipping between the two &#8211; <code>Either.asOption<\/code> and <code>Option.toLeft()<\/code>and <code>Option.toRight()<\/code> allow for converting between the two types. Obviously, converting from an <code>Either<\/code> to an <code>Option<\/code> loses some information in the case of a <code>Left<\/code>.<\/p>\n\n\n\n<p>In the functional world the convention of using <code>Right<\/code> to indicate success and a <code>Left<\/code> to indicate failure is very strong, with almost all uses of <code>Either<\/code> being used this way.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Try<\/h3>\n\n\n\n<p>Exceptions have been a part of procedural programming languages for a very long time. Originally, hardware was capable of signalling &#8216;abnormal&#8217; conditions which should result in a &#8216;pause&#8217; of normal operations in order to handle whatever caused the condition. That idea grew into the software exception handling we see today. In general, functional style languages attempt to signal all responses through the return value. Exceptions break this model by having an alternative return mechanism, creating complexity in the language and the caller. Unfortunately, much of the code in real-world libraries utilises exception throwing. The <code>Try[T]<\/code> type is designed to ease interaction with such code.<\/p>\n\n\n\n<p>A <code>Try[T]<\/code> represents the result of a computation which may have returned an exception <strong>or<\/strong>  a value of type <code>T<\/code>. In many ways a <code>Try[T]<\/code> is very similar to an <code>Either[A,T]<\/code>where <code>A<\/code> is an Exception. There are two subtypes of <code>Try<\/code> &#8211; a <code>Success[T]<\/code> and a <code>Failure[T]<\/code> allowing for effective pattern matching. It also allows for <code>map<\/code>-ing and <code>flatMap<\/code>-ing over its contents, collapsing to a value with a default in the exception case using <code>orElse<\/code>, or allowing exceptions to be handled using <code>recover<\/code> or <code>recoverWith<\/code>. A failure can also be mapped using the <code>transform<\/code> method. To help interact with other functional types there are also <code>toOption<\/code> and <code>toEither<\/code> methods.<\/p>\n\n\n\n<p>With <code>Try<\/code> we can wrap calls to an external, third-party, exception-using library and then process the results functionally. This allows us to isolate exception handling to the edges of the application with core application processing not having to worry about exceptions at all.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Tuple<\/h3>\n\n\n\n<p>A <code>tuple<\/code> is just a loose collection of heterogeneous items. In Scala they look a lot like a sequence, but we can directly address them by ordinal. Unlike a sequence they have a fixed length with fixed types in each position. We generally use them in functional programming as a means of loosely coupling related items in an intermediate processing step. For example, if I have two sequences of integers and I want to find a sequence containing the pairwise sum of each one way of achieving that would be to zip the sequences together, producing a single sequence of tuples and then mapping over the sequence adding each tuple.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">val list1: Seq[Int] = Seq(1, 2, 3)\nval list2: Seq[Int] = Seq(5, 6, 7)\nval intermediate: Seq[(Int, Int)] = list1.zip(list2)\nintermediate.map(_._1 + _._2)<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>All of the types presented here represent a value which is some generic form of composition of multiple types. These types are not unique to the functional world, but they have emerged from that world. By separating out <code>null<\/code> into a special case the <code>Option<\/code> type ensures it is handled appropriately when it needs to be and can be ignored when it doesn&#8217;t. More generically, the <code>Either<\/code> type allows any method to return one of two distinct types, and allows for generic error handling and presentation. The <code>Try<\/code> represents a specialisation of that mechanism tailored for interacting with library or legacy code which uses exceptions. Finally the <code>Tuple<\/code> allows a function to easily return multiple values without having to instantiate a distinct type to represent the combination. Where the combination occurs infrequently this is quick and easy. Later refactoring can then easily introduce a combination type <strong>if<\/strong> that proves valuable.<\/p>\n\n\n\n<p>What we see from all this is how extensively the functional paradigm attempts to make use of types and the type system to signal complex, and sometimes disjoint, return values from functions. We bring return values into a single place, we never modify input parameters and we don&#8217;t complicate function signatures with exception specifications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Functional programming tries to use return types to convey information. This is particularly important when it comes to errors and failures. Procedural approaches have used exceptions, sentinel values, mutable parameters and return codes to convey &#8216;extra&#8217; information about the result of a call. However, not all of these are appropriate in a pure functional world. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-163","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Fundamental Functional Types - Pragmatic Software Engineering<\/title>\n<meta name=\"description\" content=\"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Fundamental Functional Types - Pragmatic Software Engineering\" \/>\n<meta property=\"og:description\" content=\"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\" \/>\n<meta property=\"og:site_name\" content=\"Pragmatic Software Engineering\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-14T10:59:19+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-08T14:53:18+00:00\" \/>\n<meta name=\"author\" content=\"alastair\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"alastair\" \/>\n\t<meta name=\"twitter:label2\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\"},\"author\":{\"name\":\"alastair\",\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1\"},\"headline\":\"Fundamental Functional Types\",\"datePublished\":\"2023-04-14T10:59:19+00:00\",\"dateModified\":\"2023-05-08T14:53:18+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\"},\"wordCount\":1326,\"publisher\":{\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1\"},\"articleSection\":[\"Uncategorized\"],\"inLanguage\":\"en-GB\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\",\"url\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\",\"name\":\"Fundamental Functional Types - Pragmatic Software Engineering\",\"isPartOf\":{\"@id\":\"https:\/\/blog.adonlon.org\/#website\"},\"datePublished\":\"2023-04-14T10:59:19+00:00\",\"dateModified\":\"2023-05-08T14:53:18+00:00\",\"description\":\"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.\",\"breadcrumb\":{\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/blog.adonlon.org\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Fundamental Functional Types\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/blog.adonlon.org\/#website\",\"url\":\"https:\/\/blog.adonlon.org\/\",\"name\":\"Pragmatic Software Engineering\",\"description\":\"Random thoughts and insights on software engineering\",\"publisher\":{\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/blog.adonlon.org\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-GB\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1\",\"name\":\"alastair\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/cf9abf1220f449fccd0f6795d12b05cb?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/cf9abf1220f449fccd0f6795d12b05cb?s=96&d=mm&r=g\",\"caption\":\"alastair\"},\"logo\":{\"@id\":\"https:\/\/blog.adonlon.org\/#\/schema\/person\/image\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Fundamental Functional Types - Pragmatic Software Engineering","description":"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/","og_locale":"en_GB","og_type":"article","og_title":"Fundamental Functional Types - Pragmatic Software Engineering","og_description":"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.","og_url":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/","og_site_name":"Pragmatic Software Engineering","article_published_time":"2023-04-14T10:59:19+00:00","article_modified_time":"2023-05-08T14:53:18+00:00","author":"alastair","twitter_card":"summary_large_image","twitter_misc":{"Written by":"alastair","Estimated reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#article","isPartOf":{"@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/"},"author":{"name":"alastair","@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1"},"headline":"Fundamental Functional Types","datePublished":"2023-04-14T10:59:19+00:00","dateModified":"2023-05-08T14:53:18+00:00","mainEntityOfPage":{"@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/"},"wordCount":1326,"publisher":{"@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1"},"articleSection":["Uncategorized"],"inLanguage":"en-GB"},{"@type":"WebPage","@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/","url":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/","name":"Fundamental Functional Types - Pragmatic Software Engineering","isPartOf":{"@id":"https:\/\/blog.adonlon.org\/#website"},"datePublished":"2023-04-14T10:59:19+00:00","dateModified":"2023-05-08T14:53:18+00:00","description":"An overview of some of the fundamental types used in the functional programming paradigm and how they can be used to improve structure.","breadcrumb":{"@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/blog.adonlon.org\/index.php\/2023\/04\/14\/fundamental-functional-types\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.adonlon.org\/"},{"@type":"ListItem","position":2,"name":"Fundamental Functional Types"}]},{"@type":"WebSite","@id":"https:\/\/blog.adonlon.org\/#website","url":"https:\/\/blog.adonlon.org\/","name":"Pragmatic Software Engineering","description":"Random thoughts and insights on software engineering","publisher":{"@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.adonlon.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-GB"},{"@type":["Person","Organization"],"@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/4c5a1b2463425db9814bf8540f8954c1","name":"alastair","image":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/cf9abf1220f449fccd0f6795d12b05cb?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/cf9abf1220f449fccd0f6795d12b05cb?s=96&d=mm&r=g","caption":"alastair"},"logo":{"@id":"https:\/\/blog.adonlon.org\/#\/schema\/person\/image\/"}}]}},"_links":{"self":[{"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/posts\/163","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/comments?post=163"}],"version-history":[{"count":1,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/posts\/163\/revisions"}],"predecessor-version":[{"id":232,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/posts\/163\/revisions\/232"}],"wp:attachment":[{"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/media?parent=163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/categories?post=163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.adonlon.org\/index.php\/wp-json\/wp\/v2\/tags?post=163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}