Variant.pm

filter: Statementstmt 81.2% 117 / 144 Branchbran 53.1% 34 / 64 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 100% 16 / 16 Podpod 83.3% 5 / 6 totaltotal 73.6% 173 / 235 CC 38 SCAR 29.0
CC
38
Cov
72%
constructor
43.8
match
12.4
register_variant
6.6
CRAP 18.1
↑ Summary lambda.pl »
1 # Data::Variant.pm -- Algebraic datatypes for Perl
2 #
3 # Copyright (c) 2004-2013 Viktor Leijon (leijon@ludd.ltu.se) All rights reserved.
4 # This program is free software; you can redistribute it and/or modify
5 # it under the same terms as Perl itself.
6 #
7  
8 =head1 NAME
9  
10 Data::Variant - Variant datatypes for perl.
11  
12 =head1 SYNOPSIS
13  
14 use Data::Variant;
15 use vars qw(&Empty &Leaf &Node);
16  
17 register_variant("Tree","Empty","Leaf <NUM>","Node Tree Tree");
18 my $tree = Node((Node ((Leaf 3), (Leaf 4))), Leaf 5);
19  
20 sub printTree {
21 my $tree = shift;
22 my ($data, $left, $right);
23  
24 print "Data $data\n"
25 if (match $tree,"Leaf", $data);
26 printTree($left), printTree($right)
27 if (match $tree,"Node",$left,$right);
28 }
29  
30 =head1 DESCRIPTION
31  
32 This module offers a Haskell/O'Caml-style for variant data types. You
33 can register data types and then both construct them using the
34 constructors give, and match against them as conditionals. The best
35 way to understand what the module does is probably to look at the
36 included examples. Pattern matching together with variants is (in the
37 author's opinion) one of the very most useful features in Haskell and
38 while this implementation is very informal it serves the same
39 practical purpose.
40  
41 There is some (very limited) typechecking available to make sure that
42 you use your data structure as intended (well, as declared really but
43 if you are wise these two coincide).
44  
45 For the programmer unused to pattern matching, looking at the
46 synoposis or the examples is probably the easiest way to get an idea
47 of how to use the module.
48  
49 =head1 FUNCTIONS
50  
51 =over 4
52  
53 =cut
54  
55 package Data::Variant;
56  
57 # Requires perl 5.8.0
58 1 ▶use 5.8.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 1 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
64 1 ▶use Switch;
Subroutine BEGIN: called CC=1 SCAR=0.0
65  
66 1 our $VERSION = "0.05";
67  
68 1 our @ISA = qw(Exporter);
69 1 our @EXPORT = qw(register_variant match set_match mkpat);
70 1 our $DEBUG = 0;
71  
72 sub constructor;
73  
74 # Keep track of all existing datatypes.
75 1 our %dataTypes;
76 # This is a back-mapping from constructors to variant datatypes.
77 # Do we need both this and dataTypes? Yes, it is handy.
78 1 our %constructors;
79 # This is the object pre-set for following calls to match
80 1 our $matchObject;
81  
82 =item register_variant(NAME [, CONSTRUCTORS])
83  
84 This function registers a variant with the module. The C<NAME> should
85 be a string uniquely naming the variant.
86  
87 Next should come a list of constructors. A constructor can come in one
88 of two forms:
89  
90 =over 8
91  
92 =item * A list reference
93  
94 The first element of the list should be a string, containing the name
95 of the constructor. This name will be the name of the constructor
96 function that will be used to construct new instances of this
97 variant. By convention constructors start with a capital letter.
98  
99 The other elements should be strings indicating the type of the
100 variable stored in this position.
101  
102 We are allowed the following types in this version:
103  
104 =over 12
105  
106 =item * C<< <NUM> >> - Numbers
107  
108 =item * C<< <STRING> >> - Strings
109  
110 =item * C<< <REF> >> - References
111  
112 =item * C<< * >> - wildcard, allow any type for this field
113  
114 =item * I< Type > - allow only other variants of I<Type>.
115  
116 =back
117  
118 This information is later used for some basic typechecking, see
119 L</"Typechecking">.
120  
121 =item * A single string
122  
123 The string should just be a space separated list, basically containing
124 the same as if it was list reference instead.
125  
126  
127 =back
128  
129 B<NOTE: > The constructor has to be globally unique within your program.
130  
131 Examples:
132
133 # Registers the variant Tree with the constructors:
134 # Empty, Leaf and Node.
135 # The Empty node carries no data, the leaf node carries an int
136 # and an internal node carries two subtrees.
137 register_variant("Tree","Empty","Leaf <NUM>","Node Tree Tree");
138  
139 # Essentially the same, but using list reference form.
140 register_variant("Tree2", ["Empty2"],["Leaf2","<NUM>"],["Node2", "Tree2","Tree2"]);
141  
142 # The Maybe type from Haskell, often called an "optional value".
143 register_variant("Maybe", "Nothing", "Just *");
144  
145 =cut
146  
147 1 ▶sub register_variant {
Subroutine register_variant: called CC=6 SCAR=18.9
Pod documented
148 1 my $dt = shift;
149  
150 1 ▶ if (exists $dataTypes{$dt}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Data::Variant::dataTypes{$dt}) 0 1 1
151 0 carp "Registering datatype $dt twice";
152 }
153  
154 1 my %altHash;
155 1 ▶ while($_ = shift) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ = shift()) 3 1 4
156 3 my ($con,@fields);
157  
158 # The function can be called either with space separated strings
159 # or with array references.
160 3 ▶ if (ref $_) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_) { } 0 3 3
161 0 ($con, @fields) = @{$_};
162 } else {
163 3 ($con, @fields) = split;
164 }
165  
166 carp "The constructor $con is repeated. in $dt\n"
167 3 ▶ if exists $altHash{$con};
Branch: 1 branch
BranchTrueFalseTotal
if exists $altHash{$con} 0 3 3
168  
169 3 $altHash{$con} = \@fields;
170 3 $constructors{$con} = $dt;
171 }
172
173  
174 1 $dataTypes{$dt} = \%altHash;
175 1 ▶ print Dumper(\%dataTypes) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Data::Variant::DEBUG 0 1 1
176  
177 # Last, export this variant to the caller so he gets the constructors.
178 1 export_variant($dt,caller());
179  
180 1 return 1;
181 }
182  
183 =item export_variant(VARIANT)
184  
185 =item $val->export_variant
186  
187 As a function, this function exports the variant named by the argument
188 C<VARIANT> to the calling module, making the constructors available in
189 the module.
190  
191 As a method call, on an object that is a variant value, it exports the
192 constructors for the variant that the object is an instance of.
193  
194 =cut
195  
196 1 ▶sub export_variant {
Subroutine export_variant: called CC=4 SCAR=13.9
Pod documented
197 1 my ($dt,$module) = @_;
198  
199 # This function is also called by register_variant.
200 1 ▶ $module = defined $module ? $module : caller;
Branch: 1 branch
BranchTrueFalseTotal
defined $module ? : 1 0 1
201
202 1 ▶ $dt = $dt->{Type} if $dt->isa("Data::Variant");
Branch: 1 branch
BranchTrueFalseTotal
if $dt->isa("Data::Variant") 0 1 1
203  
204 # We need to export all symbols to the caller so we can use them to
205 # construct new instances of the variant.
206 1 foreach my $cons (keys %{$dataTypes{$dt}}) {
207 1 ▶ no strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
208 3 ▶ *{"$module\::$cons"} = sub { constructor($cons, @_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
209 }
210  
211 1 1;
212 }
213  
214 =item Constructor([VARLIST])
215  
216 The constructors that you gave C<register_variant> will be exported as
217 functions to the calling package, and are used to create new instances
218 of the variant. It is during this instantiation phase that type
219 checking is performed.
220  
221 Note that if you want to use the functions without paranteses, or if
222 you have warnings turned on (and you probably should) you will have to
223 predeclare your constructors somehow, either by C<use vars qw{&Cons}>
224 or by C<sub Cons>.
225  
226 B<Note: > The constructor will return an object with the appropriate data.
227  
228 Examples:
229  
230 # Creation of some simple trees
231 my $left = Node ((Leaf 1), (Leaf 4));
232 my $right = Node ((Leaf 3), Empty);
233 my $tree = Node $left, $right;
234  
235 # A few maybe variants
236 my $nth = Nothing
237 my $sth = Just "A string";
238  
239  
240  
241 =cut
242  
243 4 ▶sub constructor {
Subroutine constructor: called CC=17 SCAR=37.8
Pod undocumented
244 4 my $cons = shift;
245
246 croak "Tried to use non-existing constructor $cons"
247 4 ▶ unless (exists $constructors{$cons});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $Data::Variant::constructors{$cons} 0 4 4
248  
249 4 my $type = $constructors{$cons};
250  
251 # This is the actual data object
252 4 my $object = { Type => $type, Cons => $cons };
253  
254 # Assign all the fields.
255 4 my @fields = @{$dataTypes{$type}->{$cons}};
256 4 my @vals;
257 4 foreach my $index (0..$#fields) {
258 6 my $var = $fields[$index];
259 6 my $val = shift;
260 6 ▶ carp "Missing argument $var for constructor $cons"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 6 6
261 unless (defined $val);
262  
263 6 ▶ print "Setting $val = $var (cons: $cons)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $Data::Variant::DEBUG 0 6 6
264 if ($DEBUG);
265  
266 # Simple run time typechecking.
267 6 my $badtype = 0;
268 6 switch ($var) {
269 # Tests "borrowed" from Switch.pm
270 0 ▶ case "<NUM>" { $badtype = 1 unless ((~$val&$val) eq 0) }
Branch: 2 branches
BranchTrueFalseTotal
if (&Switch::case("<NUM>")) 2 4 6
unless (~$val & $val) eq 0 0 2 2
271 0 ▶ case "<STRING>" { $badtype = 1 unless (ref $val eq "") }
Branch: 2 branches
BranchTrueFalseTotal
if (&Switch::case("<STRING>")) 0 4 4
unless ref $val eq "" 0 0 0
272 0 ▶ case "<REF>" { $badtype = 1 unless ref $val }
Branch: 2 branches
BranchTrueFalseTotal
if (&Switch::case("<REF>")) 0 4 4
unless ref $val 0 0 0
273 0 ▶ case "*" { $badtype = 0 }
Branch: 1 branch
BranchTrueFalseTotal
if (&Switch::case('*')) { } 0 4 4
274 else { # Variant type!
275 $badtype = 1 unless (($val->isa("Data::Variant")) &&
276 4 ▶ $val->{Type} eq $var);
Branch: 1 branch
BranchTrueFalseTotal
unless $val->isa("Data::Variant") and $val->{"Type"} eq $var 0 4 4
Condition33%1/3
$val->isa("Data::Variant") and $val->{"Type"} eq $var
!ll&&!rl&&r
004
MC/DC0%0/2
$val->isa("Data::Variant") and $val->{"Type"} eq $var
$val->isa("Data::Variant") $val->{"Type"} eq $var
Truth table33%1/3
A and B
A= $val->isa("Data::Variant")B= $val->{"Type"} eq $var
ABresult
0X0
100
111
277 }
278 4 }
279
280  
281 6 ▶ carp "Bad type, expected $var in position ".($index+1)." for $cons"
Branch: 1 branch
BranchTrueFalseTotal
if $badtype 0 6 6
282 if $badtype;
283  
284 6 push @vals, $val;
285 }
286  
287 4 $object->{VALS} = \@vals;
288  
289 4 ▶ croak "Too many arguments for constructor $cons"
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 0 0 4 4
290 if (@_ > 0);
291  
292 4 bless $object;
293  
294 4 ▶ print Dumper(\$object)
Branch: 1 branch
BranchTrueFalseTotal
if $Data::Variant::DEBUG 0 4 4
295 if $DEBUG;
296  
297 4 return $object;
298 }
299  
300 =item match([OBJ], CONS, [VARLIST])
301  
302 =item $obj->match(CONS,[VARLIST]
303  
304 =item match(OBJ)
305  
306 In its first two forms C<match> checks is C<OBJ> is constructed using
307 the constructor C<CONS> given. If it matches the variables in
308 C<VARLIST> are filled with the values of the fields of the object.
309  
310 The number of elements in C<VARLIST> must match the number of values
311 in the object.
312  
313 The first argument C<OBJ> can be left out if it has been pre-set using
314 C<set_match>.
315  
316 It its second form, with only an object as parameter, it returns a
317 function reference that is useful in a C<switch> statement. The
318 contents of each C<case> must then be created using C<mkpat>.
319  
320 =cut
321  
322 19 ▶sub match {
Subroutine match: called CC=11 SCAR=25.2
Pod documented
323 19 my $obj;
324  
325 19 ▶ if (@_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) 7 12 19
326 7 ▶ croak "A lone argument has to be a variant reference"
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0]->isa("Data::Variant") 0 7 7
327 unless $_[0]->isa("Data::Variant");
328 7 my $obj = $_[0];
329 # Create a closure and return it.
330 7 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
331 7 match($obj,@_)
332 7 };
333 }
334  
335 # Find out which object to use.
336 12 ▶ if (ref $_[0] ne "") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] ne '') { } 12 0 12
337 12 $obj = shift;
338 } else {
339 0 ▶ croak "No object pre-set" unless defined $matchObject;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Data::Variant::matchObject 0 0 0
340 0 $obj = $matchObject;
341 }
342  
343 12 ▶ croak "I need a valid object for match"
Branch: 1 branch
BranchTrueFalseTotal
unless $obj->isa("Data::Variant") 0 12 12
344 unless $obj->isa("Data::Variant");
345  
346 12 my $constr = shift;
347  
348 12 my $reqtype = $constructors{$constr};
349
350 12 ▶ if ($reqtype ne $obj->{Type}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reqtype ne $obj->{"Type"}) 0 12 12
351 0 carp "Non matching datatype. Has $obj->{Type} expected $reqtype";
352 # You know, if this was Haskell this would have been a
353 # static type error to begin with.
354 }
355
356 12 ▶ if ($obj->{Cons} ne $constr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->{'Cons'} ne $constr) { } 4 8 12
357 # Not a match
358 4 return 0;
359 } else {
360 # A match.
361  
362 # 1) Bind all variables
363 # YYY: Can we detect unbindables??
364 8 my $valsize = $#{$obj->{VALS}} + 1;
365 8 ▶ carp "Wrong number of parameters to $constr matching"
Branch: 1 branch
BranchTrueFalseTotal
if $valsize != @_ 0 8 8
366 if ($valsize != @_);
367  
368 8 foreach my $v (0..$valsize) {
369 18 ▶ if (ref $_[$v]) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[$v]) { } 5 13 18
370 5 ${$_[$v]} = $obj->{VALS}->[$v];
371 } else {
372 13 $_[$v] = $obj->{VALS}->[$v];
373 }
374 }
375  
376 # 2) return true
377 8 return 1;
378 }
379  
380 }
381  
382 =item mkpat(CONS, [VARLIST])
383  
384 This creates a reference to an array containing what would normally be
385 the input to match. This is mainly useful when working with C<switch>
386 statements.
387  
388 =cut
389  
390 7 ▶sub mkpat {
Subroutine mkpat: called CC=3 SCAR=11.0
Pod documented
391 7 my @rv;
392
393 7 ▶ croak "mkpat needs at least one argument"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 7 7
394 unless defined $_[0];
395
396 7 push @rv, $_[0];
397
398 7 foreach my $i (1..$#_) {
399 7 push @rv,\$_[$i];
400 }
401 7 return \@rv;
402 }
403  
404  
405 =item set_match(OBJ)
406  
407 =item $object->set_match
408  
409 Presets an object to match against so that the first parameter of
410 C<match> can be left out in subsequent calls.
411  
412 =cut
413  
414 1 ▶sub set_match {
Subroutine set_match: called CC=2 SCAR=7.2
Pod documented
415 1 $matchObject = shift;
416 1 ▶ warn "Parameter to set_match not a Data::Variant"
Branch: 1 branch
BranchTrueFalseTotal
unless $Data::Variant::matchObject->isa("Data::Variant") 0 1 1
417 unless ($matchObject->isa("Data::Variant"));
418 }
419  
420  
421 1 1;
422  
423 __END__
↑ Summary lambda.pl »