Skip to content

Instantly share code, notes, and snippets.

@Xliff
Created December 18, 2016 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xliff/bbe5b1d12a6926f815a0b2bb8bfed2c1 to your computer and use it in GitHub Desktop.
Save Xliff/bbe5b1d12a6926f815a0b2bb8bfed2c1 to your computer and use it in GitHub Desktop.

I've been trying to set up an enum that represents orders of magnitude in an easy to understand way.

Originally, I started out with:

enum Magnitude is export (
  'T'  => 1e12,
  'G'  => 1e9,
  'M'  => 1e6,
  'k'  => 1000,
  'h'  => 100,
  'da' => 10,
  'd'  => .1,
  'c'  => .01,
  'm'  => .001,
  'u'  => 1e-6,
  'µ'  => 1e-6,
  'n'  => 1e-9,
  'dn' => 1e-10,
  'p'  => 1e-12,
  'f'  => 1e-15
);

Thinking that would be fairly straight forward, but for some reason, rakudo parsed it as the following object;

Map.new(("G\t1000000000" => 1,"M\t1000000" => 2,"T\t1000000000000" => 0,"c\t0.01" => 7,"d\t0.1" => 6,"da\t10" => 5,"dn\t1e-10" => 12,"f\t1e-15" => 14,"h\t100" => 4,"k\t1000" => 3,"m\t0.001" => 8,"n\t1e-09" => 11,"p\t1e-12" => 13,"u\t1e-06" => 9,"µ\t1e-06" => 10))

So I figured I would remove the quotes, figuring that was the problem. So this:

enum Magnitude is export (
  'T'  => 1e12,
  'G'  => 1e9,
  'M'  => 1e6,
  'k'  => 1000,
  'h'  => 100,
  'da' => 10,
  'd'  => .1,
  'c'  => .01,
  'm'  => .001,
  'u'  => 1e-6,
  'µ'  => 1e-6,
  'n'  => 1e-9,
  'dn' => 1e-10,
  'p'  => 1e-12,
  'f'  => 1e-15
);

Got me this:

Type error in enum. Got 'Int' Expected: 'Num'

For the life of me I couldn't figure it out. Tried something like the following as a test case:

enum Magnitude('T' => 1e12, 'f' => 1e-15, d => 1e-1); say Magnitude.enums

Which worked!

Map.new((:T(1000000000000e0),:d(0.1e0),:f(1e-15)))

So now I have the following:

enum Magnitude is export (
  T  => 1e12,
  G  => 1e9,
  M  => 1e6,
  k  => 1e3,
  h  => 1e2,
  da => 1e1,
  d  => 1e-1,
  c  => 1e-2,
  m  => 1e-3,
  u  => 1e-6,
  µ  => 1e-6,
  n  => 1e-9,
  dn => 1e-10,
  p  => 1e-12,
  f  => 1e-15
);

Which gets me what I wanted:

Map.new((:G(1000000000e0),:M(1000000e0),:T(1000000000000e0),:c(0.01e0),:d(0.1e0),:da(10e0),:d      n(1e-10),:f(1e-15),:h(100e0),:k(1000e0),:m(0.001e0),:n(1e-09),:p(1e-12),:u(1e-06),:µ(1e-06)))

But it's the only way to do it, since any other way will break with the above type error.

Is this the intended behavior?

Thanks, #perl6.

@Xliff
Copy link
Author

Xliff commented Nov 23, 2020

Of course... the first version mixed Ints with Nums. LOL!

4 years later, and the answer is obvious. That's experrience for ya.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment