× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to convert my thoughts in OOP to Haskell?

Carsten König
Jul 17, 2015
<p>Ok I'll try to help a bit.</p> <p>First: I assume you have these data types:</p> <pre><code>data E1 = E1 String data E2 = E2 Int </code></pre> <p>And you have a sensible operation on both that I'll call <code>say</code>:</p> <pre><code>say1 :: E1 -&gt; String -&gt; String say1 (E1 s) msg = msg ++ s say2 :: E2 -&gt; String -&gt; String say2 (E2 i) msg = msg ++ show i </code></pre> <p>So what you can do without any type-classes or stuff is this:</p> <pre><code>type Messanger = String -&gt; String </code></pre> <p>and instead of having a container with lot's of <code>E1</code> and <code>E2</code>, instead use a container with <code>Messagner</code>s:</p> <pre><code>sayHello :: [Messanger] -&gt; String sayHello = map ($ "Hello, ") sayHello [say1 (E1 "World"), say2 (E2 42)] &gt; ["Hello, World","Hello, 42"] </code></pre> <p>I hope this helps you a bit - the thing is just going away from the object and looking at the operations instead.</p> <p>So instead of pushing the objects/data to a function that should work with the objects data and behaviour just use a common "interface" to do your stuff.</p> <p>If you give me some better example of <em>classes</em> and <em>methods</em> (for example two types that might indeed share some traits or behaviour - <code>String</code> and <code>Int</code> are really lacking on this) I will update my answer.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25030233/How%20to%20convert%20my%20thoughts%20in%20OOP%20to%20Haskell?/25036477">Stack Overflow</a>.</p>
comments powered by Disqus