Create an object/Native demonstration: Difference between revisions

Content added Content deleted
(Create an object/Native demonstration in FreeBASIC)
m (syntax highlighting fixup automation)
Line 11: Line 11:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang BASIC256>map mapa
<syntaxhighlight lang="basic256">map mapa
mapa["A"] = 65
mapa["A"] = 65
mapa["B"] = 66
mapa["B"] = 66
Line 19: Line 19:
print valor
print valor
print mapa[valor]
print mapa[valor]
next valor</lang>
next valor</syntaxhighlight>
{{out}}
{{out}}
<pre>A
<pre>A
Line 29: Line 29:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <map>
#include <utility>
#include <utility>
Line 133: Line 133:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Map intialized with values
<pre>Map intialized with values
Line 155: Line 155:
=={{header|D}}==
=={{header|D}}==
{{trans|Python}}
{{trans|Python}}
<lang d>struct DefaultAA(TK, TV) {
<syntaxhighlight lang="d">struct DefaultAA(TK, TV) {
TV[TK] standard, current;
TV[TK] standard, current;


Line 187: Line 187:
d.remove("a");
d.remove("a");
d.writeln; // ["a":1, "b":66]
d.writeln; // ["a":1, "b":66]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>["a":1, "b":2]
<pre>["a":1, "b":2]
Line 197: Line 197:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
FB doesn't have Dict natively, but we can implement them via Type
FB doesn't have Dict natively, but we can implement them via Type
<lang freebasic>Type dict
<syntaxhighlight lang="freebasic">Type dict
m1 As String*1
m1 As String*1
m2 As Integer
m2 As Integer
Line 207: Line 207:
Print mapOf(i).m1
Print mapOf(i).m1
Print mapOf(i).m2
Print mapOf(i).m2
Next i</lang>
Next i</syntaxhighlight>
{{out}}
{{out}}
<pre>A
<pre>A
Line 220: Line 220:


First create a sub-directory, romap, of the project directory and place the following package in it:
First create a sub-directory, romap, of the project directory and place the following package in it:
<lang go>package romap
<syntaxhighlight lang="go">package romap


type Romap struct{ imap map[byte]int }
type Romap struct{ imap map[byte]int }
Line 244: Line 244:
rom.imap[key] = 0 // default value of int
rom.imap[key] = 0 // default value of int
}
}
}</lang>
}</syntaxhighlight>


This package can now be imported and used within the main package as follows:
This package can now be imported and used within the main package as follows:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 269: Line 269:
i, _ = rom.Get('C')
i, _ = rom.Get('C')
fmt.Println("'C' now maps to", i)
fmt.Println("'C' now maps to", i)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 281: Line 281:
Given a list of keys and an associated list of values, the idiomatic way of expressing this concept in J would be:
Given a list of keys and an associated list of values, the idiomatic way of expressing this concept in J would be:


<lang j>lookup=: values {~ keys&i.</lang>
<syntaxhighlight lang="j">lookup=: values {~ keys&i.</syntaxhighlight>


For example:
For example:


<lang j> lookup=: 10 20 30 40 50 {~ (;:'this is a test')&i.
<syntaxhighlight lang="j"> lookup=: 10 20 30 40 50 {~ (;:'this is a test')&i.
lookup ;:'a test'
lookup ;:'a test'
30 40</lang>
30 40</syntaxhighlight>


Notes:
Notes:
Line 301: Line 301:
Java supports unmodifiable maps, sets, lists, and other more specialized unmodifiable collections. In this example, we have a unmodifiable map. We first create an ordinary map, modify as needed, then call the <code>Collections.unmodifiableMap</code>. We can subsequently read the map, but modification is not permitted. The returned map will subsequently throw a <code>UnsupportedOperationException</code> exception if a mutation operator is called. Several are demonstrated below.
Java supports unmodifiable maps, sets, lists, and other more specialized unmodifiable collections. In this example, we have a unmodifiable map. We first create an ordinary map, modify as needed, then call the <code>Collections.unmodifiableMap</code>. We can subsequently read the map, but modification is not permitted. The returned map will subsequently throw a <code>UnsupportedOperationException</code> exception if a mutation operator is called. Several are demonstrated below.


<lang java>
<syntaxhighlight lang="java">
import java.util.Collections;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashMap;
Line 346: Line 346:
}
}
</syntaxhighlight>
</lang>


{out}}
{out}}
Line 363: Line 363:
{{works with|JavaScript|1.7}}
{{works with|JavaScript|1.7}}


<lang javascript>var keyError = new Error("Invalid Key Error (FixedKeyDict)") ;
<syntaxhighlight lang="javascript">var keyError = new Error("Invalid Key Error (FixedKeyDict)") ;


function FixedKeyDict(obj)
function FixedKeyDict(obj)
Line 425: Line 425:
return "FixedKeyDict{" + s + "}" ;
return "FixedKeyDict{" + s + "}" ;
} ;
} ;
}</lang>
}</syntaxhighlight>


Test run:
Test run:


<lang javascript>
<syntaxhighlight lang="javascript">
const BR = "<BR>\n"
const BR = "<BR>\n"


Line 463: Line 463:
pl("error test : " + e.message) ;
pl("error test : " + e.message) ;
}
}
</syntaxhighlight>
</lang>


output :
output :
Line 486: Line 486:


=={{header|jq}}==
=={{header|jq}}==
jq objects are JSON objects and can be created using JSON syntax, e.g. <lang jq>{"language": "jq"}</lang>
jq objects are JSON objects and can be created using JSON syntax, e.g. <syntaxhighlight lang="jq">{"language": "jq"}</syntaxhighlight>
Objects can also be created programmatically, e.g. <lang jq>{"one": 1} + {"two": 2}</lang>
Objects can also be created programmatically, e.g. <syntaxhighlight lang="jq">{"one": 1} + {"two": 2}</syntaxhighlight>


jq objects, however, are really just values: they are immutable, and cannot be "deleted" any more than the number 1 can be deleted.
jq objects, however, are really just values: they are immutable, and cannot be "deleted" any more than the number 1 can be deleted.


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
using BackedUpImmutable
using BackedUpImmutable


Line 518: Line 518:
@test fibr["a"] == 0
@test fibr["a"] == 0
end
end
</syntaxhighlight>
</lang>
All tests pass.
All tests pass.


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 528: Line 528:
val map = mapOf('A' to 65, 'B' to 66, 'C' to 67)
val map = mapOf('A' to 65, 'B' to 66, 'C' to 67)
println(map)
println(map)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 537: Line 537:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
{{trans|C sharp}}
{{trans|C sharp}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Class LockedHash {
Class LockedHash {
Line 607: Line 607:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a[1] = "Do not modify after creation";
<syntaxhighlight lang="mathematica">a[1] = "Do not modify after creation";
a[2] = "Native demonstration";
a[2] = "Native demonstration";
Protect[a];</lang>
Protect[a];</syntaxhighlight>
Example usage:
Example usage:
<pre>a[3] = 2
<pre>a[3] = 2
Line 620: Line 620:
=={{header|Nim}}==
=={{header|Nim}}==
We leverage native stdlib table as our own object by implementing limited actual native table functionalities.
We leverage native stdlib table as our own object by implementing limited actual native table functionalities.
<lang nim>import tables, options
<syntaxhighlight lang="nim">import tables, options


type
type
Line 661: Line 661:


main()
main()
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 668: Line 668:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>package LockedHash;
<syntaxhighlight lang="perl">package LockedHash;
use parent Tie::Hash;
use parent Tie::Hash;
use Carp;
use Carp;
Line 736: Line 736:
# add a new key x: will die
# add a new key x: will die
eval { $h{x} = 1 };
eval { $h{x} = 1 };
if ($@) { print "Operation error: $@" }</lang>output:<lang>a => 3
if ($@) { print "Operation error: $@" }</syntaxhighlight>output:<syntaxhighlight lang="text">a => 3
b => 4
b => 4
c => 5
c => 5
Line 745: Line 745:
operation error: Can't add key x at test.pl line 14
operation error: Can't add key x at test.pl line 14
LockedHash::STORE('LockedHash=HASH(0x8cebe14)', 'x', 1) called at test.pl line 66
LockedHash::STORE('LockedHash=HASH(0x8cebe14)', 'x', 1) called at test.pl line 66
eval {...} called at test.pl line 66</lang>
eval {...} called at test.pl line 66</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
There is no native "read-only" setting on phix dictionaries, so the following wraps a pair of them to
There is no native "read-only" setting on phix dictionaries, so the following wraps a pair of them to
provide the requested functionality.
provide the requested functionality.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">STD</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">CUR</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">STD</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">CUR</span>
Line 832: Line 832:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Python}}==
=={{header|Python}}==
<lang python>
<syntaxhighlight lang="python">
from collections import UserDict
from collections import UserDict
import copy
import copy
Line 922: Line 922:
raise KeyError
raise KeyError
else:
else:
return super().setdefault(key, default)</lang>
return super().setdefault(key, default)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 929: Line 929:


Implementation of functions that handle fenced-hash:
Implementation of functions that handle fenced-hash:
<syntaxhighlight lang="racket">
<lang Racket>
;(struct fenced-hash (actual original) ...)
;(struct fenced-hash (actual original) ...)


Line 967: Line 967:
;private custom-write ;mode is ignored
;private custom-write ;mode is ignored
(write-string "#fenced-hash" port)
(write-string "#fenced-hash" port)
(write (hash->list (fenced-hash-actual dict)) port))</lang>
(write (hash->list (fenced-hash-actual dict)) port))</syntaxhighlight>


Definition of the actual structure and a “public” creator:
Definition of the actual structure and a “public” creator:
<lang Racket>(struct fenced-hash (actual original)
<syntaxhighlight lang="racket">(struct fenced-hash (actual original)
#:extra-constructor-name *fenced-hash ;private constructor
#:extra-constructor-name *fenced-hash ;private constructor
#:omit-define-syntaxes ;not sure this is a good idea
#:omit-define-syntaxes ;not sure this is a good idea
Line 990: Line 990:
(define (fenced-hash . args) ; public constructor
(define (fenced-hash . args) ; public constructor
(define original (apply hash args))
(define original (apply hash args))
(*fenced-hash (hash-copy original) original))</lang>
(*fenced-hash (hash-copy original) original))</syntaxhighlight>


'''Example:''' Use the fenced-hash functions:
'''Example:''' Use the fenced-hash functions:
<lang Racket>(define d (fenced-hash "a" 1 "b" 2))
<syntaxhighlight lang="racket">(define d (fenced-hash "a" 1 "b" 2))


(displayln d)
(displayln d)
Line 1,005: Line 1,005:
(displayln d)
(displayln d)
(fenced-hash-remove! d "a")
(fenced-hash-remove! d "a")
(displayln d)</lang>
(displayln d)</syntaxhighlight>
{{out}}
{{out}}
<pre>#fenced-hash(("b" . 2) ("a" . 1))
<pre>#fenced-hash(("b" . 2) ("a" . 1))
Line 1,014: Line 1,014:


'''Example (continued):''' Use the same object as a dict. The dict-clear! method is not defined, so we must call fenced-hash-clear! instead.
'''Example (continued):''' Use the same object as a dict. The dict-clear! method is not defined, so we must call fenced-hash-clear! instead.
<lang Racket>(fenced-hash-clear! d)
<syntaxhighlight lang="racket">(fenced-hash-clear! d)
(displayln d)
(displayln d)
(dict-set! d "a" 55)
(dict-set! d "a" 55)
Line 1,025: Line 1,025:
(displayln d)
(displayln d)
(dict-remove! d "a")
(dict-remove! d "a")
(displayln d)</lang>
(displayln d)</syntaxhighlight>
{{out}}
{{out}}
<pre>#fenced-hash(("b" . 2) ("a" . 1))
<pre>#fenced-hash(("b" . 2) ("a" . 1))
Line 1,037: Line 1,037:
{{Works with|rakudo|2016.08}}
{{Works with|rakudo|2016.08}}
Here we use delegation to handle all the normal hash methods that we don't need to override to define our new class.
Here we use delegation to handle all the normal hash methods that we don't need to override to define our new class.
<lang perl6>class FixedHash {
<syntaxhighlight lang="raku" line>class FixedHash {
has $.hash handles *;
has $.hash handles *;
method new(*@args) { self.bless: hash => Hash.new: @args }
method new(*@args) { self.bless: hash => Hash.new: @args }
Line 1,055: Line 1,055:
say $fh<c>; # Nil
say $fh<c>; # Nil
$fh<c> = 43; # error
$fh<c> = 43; # error
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>(1 2)
<pre>(1 2)
Line 1,068: Line 1,068:
By defining [http://design.raku.org/S12.html#FALLBACK_methods FALLBACK] any class can handle undefined method calls. Since any class inherits plenty of methods from <tt>Any</tt> our magic object will be more of a novice conjurer then a master wizard proper.
By defining [http://design.raku.org/S12.html#FALLBACK_methods FALLBACK] any class can handle undefined method calls. Since any class inherits plenty of methods from <tt>Any</tt> our magic object will be more of a novice conjurer then a master wizard proper.


<lang perl6>class Magic {
<syntaxhighlight lang="raku" line>class Magic {
has %.hash;
has %.hash;
multi method FALLBACK($name, |c) is rw { # this will eat any extra parameters
multi method FALLBACK($name, |c) is rw { # this will eat any extra parameters
Line 1,082: Line 1,082:
$magic.foo = 10;
$magic.foo = 10;
say $magic.foo;
say $magic.foo;
$magic.defined = False; # error</lang>
$magic.defined = False; # error</syntaxhighlight>


{{output}}
{{output}}
Line 1,090: Line 1,090:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Create an object/Native demonstration
# Project : Create an object/Native demonstration


Line 1,098: Line 1,098:
map["C"] = 67
map["C"] = 67
see map + nl
see map + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,111: Line 1,111:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9}}
{{works with|Ruby|1.9}}
<lang ruby># A FencedHash acts like a Hash, but with a fence around its keys.
<syntaxhighlight lang="ruby"># A FencedHash acts like a Hash, but with a fence around its keys.
# One may change its values, but not its keys. Any attempt to insert
# One may change its values, but not its keys. Any attempt to insert
# a new key raises KeyError. One may delete a key, but this only
# a new key raises KeyError. One may delete a key, but this only
Line 1,354: Line 1,354:
keys.map {|key| self[key]}
keys.map {|key| self[key]}
end
end
end</lang>
end</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/OuVZ3bT/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/qW5qzmdKSZSyAbZEqDROoA Scastie (remote JVM)].
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/OuVZ3bT/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/qW5qzmdKSZSyAbZEqDROoA Scastie (remote JVM)].
<lang Scala>object CreateMapObject extends App {
<syntaxhighlight lang="scala">object CreateMapObject extends App {
val map = Map('A' -> 65, 'B' -> 66, 'C' -> 67)
val map = Map('A' -> 65, 'B' -> 66, 'C' -> 67)


println(map)
println(map)
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
This solution uses a dict(ionary), so requires Tcl 8.5 or better. Variable traces are used to detect write or unset access to such a protected variable, restore it to the backup value at protection time, and throw an exception
This solution uses a dict(ionary), so requires Tcl 8.5 or better. Variable traces are used to detect write or unset access to such a protected variable, restore it to the backup value at protection time, and throw an exception


<lang Tcl>proc protect _var {
<syntaxhighlight lang="tcl">proc protect _var {
upvar 1 $_var var
upvar 1 $_var var
trace add variable var {write unset} [list protect0 $var]
trace add variable var {write unset} [list protect0 $var]
Line 1,381: Line 1,381:
puts "trying: $cmd"
puts "trying: $cmd"
if [catch {uplevel 1 $cmd} msg] {puts $msg}
if [catch {uplevel 1 $cmd} msg] {puts $msg}
}</lang>
}</syntaxhighlight>
Testing:
Testing:
dict set dic 1 one
dict set dic 1 one
Line 1,404: Line 1,404:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>class FixedSizeMap {
<syntaxhighlight lang="ecmascript">class FixedSizeMap {
construct new(map) {
construct new(map) {
// copy the map so it cannot be mutated from the original reference
// copy the map so it cannot be mutated from the original reference
Line 1,456: Line 1,456:
System.print(fsm.values.toList)
System.print(fsm.values.toList)
for (me in fsm) System.print([me.key, me.value])
for (me in fsm) System.print([me.key, me.value])
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,474: Line 1,474:
=={{header|zkl}}==
=={{header|zkl}}==
zkl has two dictionary objects: SD, a small dictionary that is created immutable and the "regular" dictionary has has a makeReadOnly method. They both behave the same when locked down.
zkl has two dictionary objects: SD, a small dictionary that is created immutable and the "regular" dictionary has has a makeReadOnly method. They both behave the same when locked down.
<lang zkl>d:=SD("one",1,"two",2);
<syntaxhighlight lang="zkl">d:=SD("one",1,"two",2);
d.keys; //-->L("one","two")
d.keys; //-->L("one","two")
d["one"]; //-->1
d["one"]; //-->1
d.add("three",3); // error thrown
d.add("three",3); // error thrown
d.pop("one") // error thrown</lang>
d.pop("one") // error thrown</syntaxhighlight>