Create an object/Native demonstration: Difference between revisions

m
syntax highlighting fixup automation
(Create an object/Native demonstration in FreeBASIC)
m (syntax highlighting fixup automation)
Line 11:
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">map mapa
mapa["A"] = 65
mapa["B"] = 66
Line 19:
print valor
print mapa[valor]
next valor</langsyntaxhighlight>
{{out}}
<pre>A
Line 29:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <utility>
Line 133:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Map intialized with values
Line 155:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">struct DefaultAA(TK, TV) {
TV[TK] standard, current;
 
Line 187:
d.remove("a");
d.writeln; // ["a":1, "b":66]
}</langsyntaxhighlight>
{{out}}
<pre>["a":1, "b":2]
Line 197:
=={{header|FreeBASIC}}==
FB doesn't have Dict natively, but we can implement them via Type
<langsyntaxhighlight lang="freebasic">Type dict
m1 As String*1
m2 As Integer
Line 207:
Print mapOf(i).m1
Print mapOf(i).m2
Next i</langsyntaxhighlight>
{{out}}
<pre>A
Line 220:
 
First create a sub-directory, romap, of the project directory and place the following package in it:
<langsyntaxhighlight lang="go">package romap
 
type Romap struct{ imap map[byte]int }
Line 244:
rom.imap[key] = 0 // default value of int
}
}</langsyntaxhighlight>
 
This package can now be imported and used within the main package as follows:
<langsyntaxhighlight lang="go">package main
 
import (
Line 269:
i, _ = rom.Get('C')
fmt.Println("'C' now maps to", i)
}</langsyntaxhighlight>
 
{{out}}
Line 281:
Given a list of keys and an associated list of values, the idiomatic way of expressing this concept in J would be:
 
<langsyntaxhighlight lang="j">lookup=: values {~ keys&i.</langsyntaxhighlight>
 
For example:
 
<langsyntaxhighlight lang="j"> lookup=: 10 20 30 40 50 {~ (;:'this is a test')&i.
lookup ;:'a test'
30 40</langsyntaxhighlight>
 
Notes:
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.
 
<langsyntaxhighlight lang="java">
import java.util.Collections;
import java.util.HashMap;
Line 346:
}
</syntaxhighlight>
</lang>
 
{out}}
Line 363:
{{works with|JavaScript|1.7}}
 
<langsyntaxhighlight lang="javascript">var keyError = new Error("Invalid Key Error (FixedKeyDict)") ;
 
function FixedKeyDict(obj)
Line 425:
return "FixedKeyDict{" + s + "}" ;
} ;
}</langsyntaxhighlight>
 
Test run:
 
<langsyntaxhighlight lang="javascript">
const BR = "<BR>\n"
 
Line 463:
pl("error test : " + e.message) ;
}
</syntaxhighlight>
</lang>
 
output :
Line 486:
 
=={{header|jq}}==
jq objects are JSON objects and can be created using JSON syntax, e.g. <langsyntaxhighlight lang="jq">{"language": "jq"}</langsyntaxhighlight>
Objects can also be created programmatically, e.g. <langsyntaxhighlight lang="jq">{"one": 1} + {"two": 2}</langsyntaxhighlight>
 
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}}==
<syntaxhighlight lang="julia">
<lang Julia>
using BackedUpImmutable
 
Line 518:
@test fibr["a"] == 0
end
</syntaxhighlight>
</lang>
All tests pass.
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 528:
val map = mapOf('A' to 65, 'B' to 66, 'C' to 67)
println(map)
}</langsyntaxhighlight>
 
{{out}}
Line 537:
=={{header|M2000 Interpreter}}==
{{trans|C sharp}}
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Class LockedHash {
Line 607:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">a[1] = "Do not modify after creation";
a[2] = "Native demonstration";
Protect[a];</langsyntaxhighlight>
Example usage:
<pre>a[3] = 2
Line 620:
=={{header|Nim}}==
We leverage native stdlib table as our own object by implementing limited actual native table functionalities.
<langsyntaxhighlight lang="nim">import tables, options
 
type
Line 661:
 
main()
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 668:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">package LockedHash;
use parent Tie::Hash;
use Carp;
Line 736:
# add a new key x: will die
eval { $h{x} = 1 };
if ($@) { print "Operation error: $@" }</langsyntaxhighlight>output:<syntaxhighlight lang="text">a => 3
b => 4
c => 5
Line 745:
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
eval {...} called at test.pl line 66</langsyntaxhighlight>
 
=={{header|Phix}}==
There is no native "read-only" setting on phix dictionaries, so the following wraps a pair of them to
provide the requested functionality.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 832:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
from collections import UserDict
import copy
Line 922:
raise KeyError
else:
return super().setdefault(key, default)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 929:
 
Implementation of functions that handle fenced-hash:
<syntaxhighlight lang="racket">
<lang Racket>
;(struct fenced-hash (actual original) ...)
 
Line 967:
;private custom-write ;mode is ignored
(write-string "#fenced-hash" port)
(write (hash->list (fenced-hash-actual dict)) port))</langsyntaxhighlight>
 
Definition of the actual structure and a “public” creator:
<langsyntaxhighlight Racketlang="racket">(struct fenced-hash (actual original)
#:extra-constructor-name *fenced-hash ;private constructor
#:omit-define-syntaxes ;not sure this is a good idea
Line 990:
(define (fenced-hash . args) ; public constructor
(define original (apply hash args))
(*fenced-hash (hash-copy original) original))</langsyntaxhighlight>
 
'''Example:''' Use the fenced-hash functions:
<langsyntaxhighlight Racketlang="racket">(define d (fenced-hash "a" 1 "b" 2))
 
(displayln d)
Line 1,005:
(displayln d)
(fenced-hash-remove! d "a")
(displayln d)</langsyntaxhighlight>
{{out}}
<pre>#fenced-hash(("b" . 2) ("a" . 1))
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.
<langsyntaxhighlight Racketlang="racket">(fenced-hash-clear! d)
(displayln d)
(dict-set! d "a" 55)
Line 1,025:
(displayln d)
(dict-remove! d "a")
(displayln d)</langsyntaxhighlight>
{{out}}
<pre>#fenced-hash(("b" . 2) ("a" . 1))
Line 1,037:
{{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.
<syntaxhighlight lang="raku" perl6line>class FixedHash {
has $.hash handles *;
method new(*@args) { self.bless: hash => Hash.new: @args }
Line 1,055:
say $fh<c>; # Nil
$fh<c> = 43; # error
</syntaxhighlight>
</lang>
{{out}}
<pre>(1 2)
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.
 
<syntaxhighlight lang="raku" perl6line>class Magic {
has %.hash;
multi method FALLBACK($name, |c) is rw { # this will eat any extra parameters
Line 1,082:
$magic.foo = 10;
say $magic.foo;
$magic.defined = False; # error</langsyntaxhighlight>
 
{{output}}
Line 1,090:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Create an object/Native demonstration
 
Line 1,098:
map["C"] = 67
see map + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,111:
=={{header|Ruby}}==
{{works with|Ruby|1.9}}
<langsyntaxhighlight 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
# a new key raises KeyError. One may delete a key, but this only
Line 1,354:
keys.map {|key| self[key]}
end
end</langsyntaxhighlight>
 
=={{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)].
<langsyntaxhighlight Scalalang="scala">object CreateMapObject extends App {
val map = Map('A' -> 65, 'B' -> 66, 'C' -> 67)
 
println(map)
}</langsyntaxhighlight>
 
=={{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
 
<langsyntaxhighlight Tcllang="tcl">proc protect _var {
upvar 1 $_var var
trace add variable var {write unset} [list protect0 $var]
Line 1,381:
puts "trying: $cmd"
if [catch {uplevel 1 $cmd} msg] {puts $msg}
}</langsyntaxhighlight>
Testing:
dict set dic 1 one
Line 1,404:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">class FixedSizeMap {
construct new(map) {
// copy the map so it cannot be mutated from the original reference
Line 1,456:
System.print(fsm.values.toList)
for (me in fsm) System.print([me.key, me.value])
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,474:
=={{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.
<langsyntaxhighlight lang="zkl">d:=SD("one",1,"two",2);
d.keys; //-->L("one","two")
d["one"]; //-->1
d.add("three",3); // error thrown
d.pop("one") // error thrown</langsyntaxhighlight>
 
 
10,327

edits