Note that there are some explanatory texts on larger screens.

plurals
  1. POVisitor Design Pattern in OCaml
    text
    copied!<p>I am attempting to implement the Visitor Design Pattern using OCaml's OO constructs and type system and am running into problems upon instantiation of an Element.</p> <pre><code>class virtual ['hrRep] employee = object method virtual receiveEvaluation : 'hrRep -&gt; unit method virtual getName : string end;; class ['hrRep] accountant myName = object (self : 'a) inherit ['hrRep]employee val name = myName method receiveEvaluation rep = rep#visitAccountant self method getName = name end;; class ['hrRep] salesman myName = object (self : 'a) inherit ['hrRep]employee val name = myName method receiveEvaluation rep = rep#visitSalesman self method getName = name end;; class virtual ['accountant, 'salesman] hrRep = object (self) method virtual visitSalesman : 'salesman -&gt; unit method virtual visitAccountant : 'accountant -&gt; unit end;; class ['employee, 'salesman] lowerLevelHRRep = object (self) inherit ['employee, 'salesman]hrRep method visitSalesman s = print_endline ("Visiting salesman "^s#getName) method visitAccountant a = print_endline ("Visiting accountant "^a#getName) end;; let s1 : (&lt;visitSalesman : 'a -&gt; unit&gt;) salesman = new salesman "Bob";; let a1 : (&lt;visitAccountant : 'a -&gt; unit&gt;) accountant = new accountant "Mary";; let s2 : (&lt;visitSalesman : 'a -&gt; unit&gt;) salesman = new salesman "Sue";; let h1 : (&lt;getName : string&gt;, &lt;getName : string&gt;) lowerLevelHRRep = new lowerLevelHRRep;; s1#receiveEvaluation h1;; </code></pre> <p>The error I get upon compilation is:</p> <pre><code>The type of this expression, &lt;visitSalesman : 'a -&gt; unit; _.. &gt; salesman as 'a, contains type variables that cannot be generalized. </code></pre> <p>However, the code compiles minus the line instantiating the <code>salesman</code>. </p> <p>How do I go about instantiating the <code>salesman</code> while maintaining the classes' functionality ?</p> <p><strong>Edit</strong> Error received with call to receiveEvaluation: </p> <pre><code>This expression has type (&lt;getName:string&gt;, &lt; getName:string&gt;) lowerLevelHRRep but is here used with type &lt;visitSalesman : 'a salesman -&gt; unit &gt; as 'a. </code></pre> <p>The second object type has no method <code>visitAccountant</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload