{"id":12526,"date":"2015-09-14T01:00:00","date_gmt":"2015-09-14T00:00:00","guid":{"rendered":"http:\/\/siejkowski.net\/typeclasses-in-swift"},"modified":"2023-04-27T11:32:41","modified_gmt":"2023-04-27T09:32:41","slug":"typeclasses-in-swift","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2015\/09\/14\/typeclasses-in-swift\/","title":{"rendered":"Typeclasses in Swift, Haskell and Scala"},"content":{"rendered":"<h2 id=\"what-is-a-typeclass\">What is a typeclass?<\/h2>\n<p>Typeclass is a Haskell way of creating the type composition in the world without inheritance. It allows to define a desired behavior in a form of function signatures. The concrete implementation is provided separately for all the required types. In other words, it splits the familiar object-oriented encapsulation (data and functionality together) in two separate parts: data and functionality. At the same time typeclass defines a contract that we can build upon. It\u2019s like defining the same function multiple times &#8211; each time the only thing that differs is the type in the signature &#8211; and making it possible to use this function in some other place without specifying which one of its variants should be used. The compiler guesses it for us.<\/p>\n<p>Doesn\u2019t it sound like Swift or Objective-C protocols? Well, it does. It\u2019s no surprise, because they\u2019re all fueled by same basic idea. This is the first and arguably the most important thing to know about typeclasses &#8211; although they do have a word <em>class<\/em> in their name, they are more similar to protocols. Actually, they are far enough from classes so they can independently coexist with them, orthogonal to each other.<\/p>\n<p>Typeclasses, being protocol cousins, are used in similar fashion: to express a feature that spreads across multiple types. In Haskell there are typeclasses like <code>Eq<\/code>, expressing that things are equatable, or <code>Ord<\/code>, expressing that they are sortable, or <code>Functor<\/code>, expressing that they can be mapped over.<\/p>\n<p>If you\u2019ve seen <a href=\"https:\/\/developer.apple.com\/videos\/wwdc\/2015\/?id=408\">WWDC 2015 session \u201cProtocol-Oriented Programming in Swift\u201d<\/a>, you\u2019re gonna feel at home (or run away screaming, depending on how you liked it). One thing to notice: while in a more strict functional language, namely Haskell, typeclass is a part of its type semantics, in Swift or Scala typeclass is more of a design pattern. We\u2019re using their native type semantics to achieve similar effects.<\/p>\n<p>Enough with introduction. Let\u2019s define a typeclass so we can more easily grasp what\u2019s going on.<\/p>\n<h2 id=\"things-that-can-be-encoded-in-ceasar-cipher\"><em>Things that can be encoded in Ceasar cipher<\/em><\/h2>\n<p>Have you heard of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Caesar_cipher\">Caesar cipher<\/a>? It is a very basic cryptography method: we express anything as a string and than we shift each letter by a fixed number of places in the alphabet. So, for 3-letter Ceasar cipher we write D instead of A, E instead of B, F instead of C and so on.<\/p>\n<p>Our typeclass is gonna describe the ability to be expressed in a Ceasar cipher form. It\u2019s gonna be based on position of particular character in the ASCII table. For the sake of simplicity I\u2019ll ignore the fact that in the ASCII table there are some special characters after the last letters of the alphabet. No one is actually sending messages to Roman legions anymore, so no one is gonna get surprised by some <code>%$#<\/code>.<\/p>\n<p>Here is the <code>Ceasarable<\/code> typeclass defined in Haskell:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Ceasarable c where \r\n\u00a0\u00a0\u00a0\u00a0toCeasar :: c -&gt; String<\/pre>\n<p>Just to mess with object-oriented minds, it uses keyword <code>class<\/code> to kick off its definition. Then it declares one function signature: <code>toCeasar<\/code>. The function takes one argument of any type and returns a string, presumably with the cipher shift applied. This is our desired behavior. It must be implemented (with the actual type instead of <code>c<\/code>) by the typeclass instances.<\/p>\n<p>How does it gonna look like in Scala? We\u2019re gonna use Scala\u2019s type semantics. The most obvious way is to use trait:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">trait Ceasarable[T] {\r\n\u00a0\u00a0\u00a0\u00a0def toCeasar(input: T): String\r\n}<\/pre>\n<\/div>\n<p>The translation is straightforward. Any type in Haskell becomes a generic parameter in Scala. The signature is the same.<\/p>\n<p>In Swift the closest thing to traits\/interfaces are protocols, so let\u2019s search no further:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">protocol Ceasarable { \r\n    typealias T static func toCeasar(input: T) -&gt; String \r\n}<\/pre>\n<p>Apart from minor syntax differences, like associated type instead of generic parameter, it\u2019s the same as in Scala. Not surprising, as those two languages share a lot of similarities (and I mean like, a lot). One thing to notice is the use of <code>static<\/code> method. Why is it static? Because we want to emulate the split between the data and behavior. If the method is not static, than it can use the instance data and there is (in our simple case) no need to pass <code>input<\/code> at all. An instance method declaration would make the typeclass a little more object-oriented, and there\u2019s nothing wrong with that, but for now let\u2019s stick to the original idea. We\u2019re providing the implementation for a type, not for an instance.<\/p>\n<h2 id=\"when-i-grow-up-i-wanna-be-a-typeclass\">When I grow up I wanna be a typeclass!<\/h2>\n<p>Once we\u2019ve defined what we expect, it\u2019d be nice to provide some actual implementations for chosen types. This way we\u2019d be able to use the behavior. Let\u2019s choose two simple types to work with: strings and integers. In Haskell, the implementation is provided by defining the concrete typeclass instance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}\r\n    \r\ninstance Ceasarable String where\r\n \u00a0\u00a0\u00a0toCeasar x = [toEnum $ fromEnum c + 3 | c &lt;- x]\r\n    \r\ninstance Ceasarable Integer where\r\n    toCeasar x = [toEnum $ fromEnum c + 3 | c &lt;- show x]<\/pre>\n<p>Keyword <code>instance<\/code> means that the implementation is coming. For String, we map over characters, get their ASCII numbers with <code>fromEnum<\/code>, add three and than encode again with <code>toEnum<\/code>. For Integer we just express it as String using <code>show<\/code> and we do exactly the same.<\/p>\n<p>In Scala things get a little weird, so feel free to skip over the details. The <code>Ceasarable<\/code> behavior is enclosed in the <code>object<\/code> and marked as implicit. This way it can be implicitly passed to the place we want to use it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">object Ceasarable {\r\n    implicit object CeasarableInt extends Ceasarable[Int] {\r\n        override def toCeasar(input: Int): String = {\r\n            s\"$input\".map(_ + 3).map(_.toChar).mkString\r\n        }\r\n    }\r\n   \r\n    implicit object CeasarableString extends Ceasarable[String] {\r\n        override def toCeasar(input: String): String = {\r\n            input.map(_ + 3).map(_.toChar).mkString\r\n        }\r\n    }\r\n}\r\n\r\n<\/pre>\n<p>The <code>object<\/code> scope and <code>implicit<\/code> passing are part of Scala peculiarities, no need to dive deeper in them. If you really want to, <a href=\"http:\/\/danielwestheide.com\/blog\/2013\/02\/06\/the-neophytes-guide-to-scala-part-12-type-classes.html\">look here<\/a>. What matters is that we\u2019ve created separated objects with <code>Ceasarable<\/code> implementations for <code>String<\/code> and <code>Int<\/code> types and we enclosed them in static-like objects (<code>object<\/code> is as close as you can get to <code>static<\/code> in Scala). Those types know nothing about their ability to be expressed in Ceasar cipher.<\/p>\n<p>Let\u2019s try the same approach in Swift:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">struct CeasarableInt : Ceasarable {\r\n    typealias T = Int\r\n    static func toCeasar(input: Int) -&gt; String {\r\n        return \"(input)\".unicodeScalars.reduce(\"\") { \r\n            (acc, char) in\r\n            return acc + String(UnicodeScalar(char.value + 3))\r\n        }\r\n    }\r\n}\r\n\r\nstruct CeasarableString : Ceasarable {\r\n    typealias T = String\r\n    static func toCeasar(input: String) -&gt; String {\r\n        return input.unicodeScalars.reduce(\"\") { \r\n            (acc, char) in\r\n            return acc + String(UnicodeScalar(char.value + 3))\r\n        }\r\n    }\r\n}\r\n\r\n<\/pre>\n<p>Looks valid. This way we\u2019ve defined the ability to be encoded in Ceasar cipher for strings and integers in each language we consider.<\/p>\n<p>Now we can work with <code>Ceasarable<\/code> objects just as with any other group of objects sharing common characteristics, i.e. type. We can declare that we expect it as function parameter, we can return it in a function result and so on. Let\u2019s see the example usages. In Haskell:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">encodeInCeasar :: (Ceasarable c) =&gt; c -&gt; String\r\nencodeInCeasar = toCeasar\r\n    \r\nencodeInCeasar 1234 -- \"4567\"\r\n    \r\nencodeInCeasar \"ABCabc\" -- \"DEFdef\"<\/pre>\n<p>We are using the typeclass just like we\u2019d use the protocol &#8211; to define a contract without explicitly defining what object are gonna conform to this contract.<\/p>\n<p>How about Scala?<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def encodeInCeasar[T: Ceasarable](c: T) = {\r\n\u00a0\u00a0\u00a0\u00a0val encoded = implicitly[Ceasarable[T]].toCeasar(c)\r\n\u00a0\u00a0\u00a0\u00a0println(encoded)\r\n}\r\n\r\nencodeInCeasar(1234) \/\/ \"4567\"\r\n\r\n    encodeInCeasar(\"ABCabc\") \/\/ \"DEFdef\"<\/pre>\n<\/div>\n<p>The sky, once again, gets a little bit cloudy. Instead of requiring the protocol confirmation, we\u2019re explicitly asking for the proper implementation using <code>implicitly<\/code>. Implicitly needs to have the implementations passed inside the function, and the enclosing scope is passed via a mechanism called context bound. <code>T: Ceasarable<\/code> is a syntax for context bound. It might sound confusing, but it\u2019s fine, actually. This way we can easily see that we\u2019re using a typeclass. In Swift, however, we encounter a problem:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func encodeInCeasar&lt;C : Ceasarable&gt;(c: C.T) -&gt; String {\r\n    return C.toCeasar(c)\r\n}\r\n\r\nencodeInCeasar(c: 1234) \/\/ Compiler error: Cannot invoke 'encodeInCeasar' with an argument list of type '(Int)'<\/pre>\n<p>Swift compiler cannot infer the generic parameter. There is a struct that does exactly what we want: conforms to <code>Ceasarable<\/code> and defines <code>Int<\/code> as its associated type. However, it cannot be found automatically. Swift doesn\u2019t have semantics for Scala-like context bound. However, we\u2019ve got the second best thing\u2026 Wait! It\u2019s actually the first best thing, only Swift is 2.0. Protocol extensions.<\/p>\n<h2 id=\"swift-typeclasses-defined-with-protocol-extensions\">Swift typeclasses defined with protocol extensions<\/h2>\n<p>In Swift we can use the <code>extension<\/code> keyword to provide implementations for already existing types. The beauty of extension lays in its two properties: universality and ability to be constraint. By universality I mean that you can extend all the Swift types: protocols, classes, structs and enums. The ability to be constraint let us express what we want to extend in a great detail &#8211; greater than allowed by protocol confirmation or class inheritance alone.<\/p>\n<p>Did I mention that if you\u2019ve watched <a href=\"https:\/\/developer.apple.com\/videos\/wwdc\/2015\/?id=408\">\u201cProtocol-Oriented Programming in Swift\u201d<\/a> you\u2019ll feel at home? Our better implementation of typeclasses starts with a slight change to the <code>Ceasarable<\/code> definition:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">protocol Ceasarable {\r\n        static func toCeasar(input: Self) -&gt; String\r\n}<\/pre>\n<p>Instead of requiring the associated type in protocol, we can add a <code>Self<\/code> requirement. This way we\u2019re expressing that for whatever type we\u2019re providing the typeclass implementation, it requires the value of that type as the parameter. It stays closer to the original Haskell definition, because the typeclass doesn\u2019t need to be generic. It is just like a template for multiple function definitions that differ only by the type in signature. <code>Self<\/code> expresses exactly that. There is also another way of expressing the same idea: see <a href=\"http:\/\/slashmesays.tumblr.com\/post\/87833542239\/type-classes-in-swift\">this article on how to do it using Swift 1.2<\/a> (spoiler alert: <code>&lt;C: Ceasarable where C.T == C&gt;<\/code>), but for Swift 2.0 the most straightforward way is with <code>Self<\/code>. The actual implementations become easier to write and more readable:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">extension Int : Ceasarable {\r\n    static func toCeasar(input: Int) -&gt; String {\r\n        return \"(input)\".unicodeScalars.reduce(\"\") { \r\n            (acc, char) in\r\n            return acc + String(UnicodeScalar(char.value + 3))\r\n        }\r\n    }\r\n}\r\n\r\nextension String : Ceasarable {\r\n    static func toCeasar(input: String) -&gt; String {\r\n        return input.unicodeScalars.reduce(\"\") { \r\n            (acc, char) in\r\n            return acc + String(UnicodeScalar(char.value + 3))\r\n        }\r\n    }\r\n}\r\n\r\n<\/pre>\n<p>It looks like a straightforward protocol confirmation and it\u2019s just what we need. Having that, the usage get simpler as well:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">func encodeInCeasar&lt;T : Ceasarable&gt;(c: T) -&gt; String {\r\n    return T.toCeasar(c)\r\n}\r\n\r\nencodeInCeasar(1234) \/\/ \"4567\"\r\n\r\nencodeInCeasar(\"ABCabc\") \/\/ \"DEFdef\"<\/pre>\n<\/div>\n<p>This is what we tried to achieve. At the same time we\u2019re providing behavior separate from data (since it\u2019s static method of <code>T<\/code>) and expressing the common functionality (since <code>T<\/code> must be <code>Ceasarable<\/code>). By using protocol extensions, we\u2019ve enabled the second dimension, somewhat orthogonal to inheritance, in which we can compose our functionalities.<\/p>\n<h2 id=\"what-are-swift-typeclasses-then\">What are Swift typeclasses, then?<\/h2>\n<p>A typeclass in Swift is a pattern build using the protocols and extensions. It\u2019s simple and there\u2019s nothing new, really, as we\u2019ve been already using those concepts extensively. As a side note, the process of learning functional programming is very often like that: concepts we used for a long time, but differently named, generalized and ready to build upon.<\/p>\n<p>Typeclasses are a way of providing a behavior for the type separately from the type and at the same time defining a contract that the type conforms to. It might be used to add functionalities and build composition without inheritance.<\/p>\n","protected":false},"excerpt":{"rendered":"What is a typeclass? Typeclass is a Haskell way of creating the type composition in the world without&hellip;\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[553,552,113,551],"class_list":{"0":"post-12526","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design","7":"tag-haskell","8":"tag-ios","9":"tag-scala","10":"tag-swift"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12526","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=12526"}],"version-history":[{"count":14,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12526\/revisions"}],"predecessor-version":[{"id":15675,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12526\/revisions\/15675"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=12526"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=12526"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=12526"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}