Active object: Difference between revisions

m
syntax highlighting fixup automation
(add FreeBASIC)
m (syntax highlighting fixup automation)
Line 21:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=ada>with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 85:
Put_Line ("Integrated" & Float'Image (S) & "s");
I.Shut_Down;
end Test_Integrator;</langsyntaxhighlight>
Sample output:
<pre>
Line 93:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang=bbcbasic> INSTALL @lib$+"CLASSLIB"
INSTALL @lib$+"TIMERLIB"
INSTALL @lib$+"NOWAIT"
Line 115:
PROCwait(50)
PRINT "Final value = " FN(myinteg.output)
PROC_discard(myinteg{})</langsyntaxhighlight>
Output:
<pre>
Line 125:
{{libheader|pthread}}
 
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 194:
 
return 0;
}</langsyntaxhighlight>
output
<pre>-9.99348e-05</pre>
Line 200:
=={{header|C sharp|C#}}==
{{works with|C# 6}}
<langsyntaxhighlight lang=csharp>using System;
using System.Threading.Tasks;
 
Line 277:
Console.WriteLine(ao.Value);
}
}</langsyntaxhighlight>
 
Output:
Line 284:
=={{header|C++}}==
{{works with|C++14|}}
<langsyntaxhighlight lang=cpp>#include <atomic>
#include <chrono>
#include <cmath>
Line 372:
std::this_thread::sleep_for(500ms);
std::cout << foo.output();
}</langsyntaxhighlight>
output
<pre>1.23136e-011</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=clojure>(ns active-object
(:import (java.util Timer TimerTask)))
 
Line 413:
user> (test-integrator)
1.414065859052494E-5
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{libheader|Bordeaux Threads}}
 
<langsyntaxhighlight lang=lisp>
(defclass integrator ()
((input :initarg :input :writer input :reader %input)
Line 502:
(format t "~F~%" (area integrator)))
(input nil integrator)))
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
{{trans|Python}}
Crystal currently runs all code in a single thread, so a trivial example wouldn't have any issues with thread safety. However, this behavior will likely change in the future. This example was written with that in mind, and is somewhat more complex to show better idioms and be future-proof.
<langsyntaxhighlight lang=ruby>require "math"
require "time"
 
Line 582:
proc_chan.send({Action::Finished, ->(t : Float64) { 0f64 }})
sleep 0.5.seconds
puts result_chan.receive</langsyntaxhighlight>
 
Output:
Line 591:
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight lang=D>import core.thread;
import std.datetime;
import std.math;
Line 663:
v0 = v1;
}
}</langsyntaxhighlight>
 
{{out}}
Line 671:
{{libheader| System.Classes}}
{{Trans|Python}}
<langsyntaxhighlight lang=Delphi>
program Active_object;
 
Line 757:
Integrator.Join;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 765:
=={{header|E}}==
 
<langsyntaxhighlight lang=e>def makeIntegrator() {
var value := 0.0
var input := fn { 0.0 }
Line 815:
})
return result
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
We use the functions (at ..) : scheduling, (wait ...), and (every ...) ot the timer.lib. The accuracy will be function of the browser's functions setTimeout and setInterval ...
<langsyntaxhighlight lang=lisp>
(require 'timer)
Line 850:
(else (error "active:bad message" message))))))
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight lang=lisp>
(define (experiment)
(define (K t) (sin (* PI t )))
Line 872:
3/7/2015 20:34:28 : result
result 0.00026510586971023164
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
I could not see what time to use between each integration so it is the argument to task().
<langsyntaxhighlight lang=Erlang>
-module( active_object ).
-export( [delete/1, input/2, new/0, output/1, task/1] ).
Line 939:
 
zero( _ ) -> 0.
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>open System
open System.Threading
 
Line 984:
 
printfn "%f" (i.Output())
i.Stop()</langsyntaxhighlight>
 
=={{header|Factor}}==
Working with dynamic quotations requires the stack effect to be known in advance. The apply-stack-effect serves this purpose.
<langsyntaxhighlight lang=factor>USING: accessors alarms calendar combinators kernel locals math
math.constants math.functions prettyprint system threads ;
IN: rosettacode.active
Line 1,028:
0.5 seconds sleep
[ output . ] [ destroy ] bi ;
MAIN: active-test</langsyntaxhighlight>
( scratchpad ) "rosettacode.active" run
-5.294207647335787e-05
Line 1,034:
=={{header|FBSL}}==
The Dynamic Assembler and Dynamic C JIT compilers integrated in FBSL v3.5 handle multithreading perfectly well. However, pure FBSL infrastructure has never been designed especially to support own multithreading nor can it handle long long integers natively. Yet a number of tasks with careful design and planning are quite feasible in pure FBSL too:
<langsyntaxhighlight lang=qbasic>#APPTYPE CONSOLE
 
#INCLUDE <Include\Windows.inc>
Line 1,127:
FUNCTION Task(BYVAL t AS DOUBLE) AS DOUBLE
RETURN SIN(2 * PI * 0.5 * t)
END FUNCTION</langsyntaxhighlight>
 
'''Typical console output:'''
Line 1,134:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>#define twopi 6.2831853071795864769252867665590057684
dim shared as double S = 0 'set up the state as a global variable
dim shared as double t0, t1, ta
Line 1,161:
 
print S
</syntaxhighlight>
</lang>
{{out}}<pre>
8.926050531860172e-07
Line 1,168:
=={{header|Go}}==
Using time.Tick to sample K at a constant frequency. Three goroutines are involved, main, aif, and tk. Aif controls access to the accumulator s and the integration function K. Tk and main must talk to aif through channels to access s and K.
<langsyntaxhighlight lang=go>package main
 
import (
Line 1,247:
time.Sleep(time.Second / 2) // 4. sleep .5 sec
fmt.Println(a.output()) // output should be near zero
}</langsyntaxhighlight>
Output:
<pre>
Line 1,255:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang=groovy>/**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
Line 1,324:
System.out.println(integrator.getOutput())
}
}</langsyntaxhighlight>
{{out}}
<pre>0.0039642136156300455</pre>
Line 1,330:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang=haskell>module Integrator (
newIntegrator, input, output, stop,
Time, timeInterval
Line 1,406:
 
-- Execute 'action' until it returns false.
whileM action = do b <- action; if b then whileM action else return ()</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,412:
Implementation:
 
<langsyntaxhighlight lang=J>coclass 'activeobject'
require'dates'
 
Line 1,435:
getoutput=:3 :0
Zero+G T''
)</langsyntaxhighlight>
 
Task example (code):
 
<langsyntaxhighlight lang=J>cocurrent 'testrig'
 
delay=: 6!:3
Line 1,455:
delay 0.5
 
smoutput (T__object,getoutput__object) ''</langsyntaxhighlight>
 
Task example (output):
Line 1,467:
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>/**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
Line 1,537:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>4.783602720556498E-13</pre>
Line 1,545:
{{trans|E}}
 
<langsyntaxhighlight lang=javascript>function Integrator(sampleIntervalMS) {
var inputF = function () { return 0.0 };
var sum = 0.0;
Line 1,570:
shutdown: function () { clearInterval(updater) },
});
}</langsyntaxhighlight>
 
Test program as a HTML fragment:
 
<langsyntaxhighlight lang=html4strict><p><span id="a">Test running...</span> <code id="b">-</code></p>
 
<script type="text/javascript">
Line 1,593:
}, 2000);
}, 1)
</script></langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,599:
Julia has inheritance of data structures and first-class types, but structures do not have methods.
Instead, methods are functions with multiple dispatch based on argument type.
<langsyntaxhighlight lang=julia>mutable struct Integrator
func::Function
runningsum::Float64
Line 1,638:
sleep(0.5)
v2 = it.runningsum
println("After 2.5 seconds, integrator value was $v2")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
Athough this is a faithful translation of the Java entry, on my machine the output of the latter is typically an order of magnitude smaller than this version. I have no idea why.
<langsyntaxhighlight lang=scala>// version 1.2.0
 
import kotlin.math.*
Line 1,711:
integrator.stop()
println(integrator.getOutput())
}</langsyntaxhighlight>
 
Sample output:
Line 1,720:
=={{header|Lingo}}==
Parent script "Integrator":
<langsyntaxhighlight lang=Lingo>property _sum
property _func
property _timeLast
Line 1,760:
me._timeLast = t
me._valueLast = val
end</langsyntaxhighlight>
 
In some movie script:
<langsyntaxhighlight lang=Lingo>global gIntegrator
 
-- entry point
Line 1,781:
put gIntegrator.output()
timer.forget()
end</langsyntaxhighlight>
 
{{out}}
Line 1,788:
=={{header|Lua}}==
Pure/native Lua is not multithreaded, so this task should perhaps be marked "omit from|Lua" if following the implicit ''intent'' of the task. However, the explicit ''wording'' of the task does not seem to require a multithreaded solution. Perhaps this is ''cheating'', but I thought it might interest the reader to see the integrator portion nonetheless, so it is demonstrated using a mock sampling method at various intervals (to ''simulate'' multithreaded updates).
<langsyntaxhighlight lang=lua>local seconds = os.clock
 
local integrator = {
Line 1,826:
sample(0.5, interval, function() i:update() end)
print(string.format("sampling interval: %f, %5d updates over 2.5s total = %.15f", interval, i.nup, i:output()))
end</langsyntaxhighlight>
{{out}}
<pre>sampling interval: 0.500000, 6 updates over 2.5s total = -0.003628054395752
Line 1,839:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>Block[{start = SessionTime[], K, t0 = 0, t1, kt0, S = 0},
K[t_] = Sin[2 Pi f t] /. f -> 0.5; kt0 = K[t0];
While[True, t1 = SessionTime[] - start;
S += (kt0 + (kt0 = K[t1])) (t1 - t0)/2; t0 = t1;
If[t1 > 2, K[t_] = 0; If[t1 > 2.5, Break[]]]]; S]</langsyntaxhighlight>
 
1.1309*10^-6
Line 1,968:
echo "Value after 0.5 more second: ", integrator.output()
integrator.destroy()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,981:
Not totally certain this is a correct implementation since the value coming out is not close to zero. It does show all of the basics of multithreading and object synchronization though.
 
<langsyntaxhighlight lang=ooRexx>
integrater = .integrater~new(.routines~sine) -- start the integrater function
call syssleep 2
Line 2,057:
::requires rxmath library
 
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
Line 2,064:
 
With a high precision timer the result is around -.0002
<langsyntaxhighlight lang=oxygenbasic>
double MainTime
 
Line 2,236:
print str(integral,4)
 
Rudolpho.clear</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang=oz>declare
fun {Const X}
fun {$ _} X end
Line 2,298:
 
{Show {I output($)}}
{I stop}</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
 
use strict;
Line 2,369:
say "0 after .5 seconds: ", $x->output;
 
$x->delete;</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 2,375:
{{libheader|Phix/Class}}
 
<!--<langsyntaxhighlight lang=Phix>-->
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.2"</span><span style="color: #0000FF;">)</span>
Line 2,441:
<span style="color: #000000;">i</span><span style="color: #0000FF;">.</span><span style="color: #000000;">stop</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">i</span><span style="color: #0000FF;">.</span><span style="color: #000000;">get_output</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
Note that were f a regular member function of the class, it would get a "this" parameter/argument, which we avoid by stashing it in a local integer prior to the call. Alternatively you could of course use zero/sine functions with an ignored parameter and the usual this.f() syntax [along with the usual "this." being optional inside the class definition].
Line 2,461:
Just lock everything, it is not that hard, and you should never need much more than the stuff below.
 
<!--<langsyntaxhighlight lang=Phix>-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">TERMINATE</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">INTERVAL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">KFUN</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">VALUE</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">T0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ID</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ISIZE</span><span style="color: #0000FF;">=$</span>
Line 2,525:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%f\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">get_output</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">stop_integrator</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dx</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 2,534:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(load "@lib/math.l")
 
(class +Active)
Line 2,577:
(wait 500) # Wait 0.5 sec
(prinl "Output: " (output> Obj)) # Print return value
(stop> Obj) ) ) # Stop active object</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<langsyntaxhighlight lang=PureBasic>Prototype.d ValueFunction(f.d, t.d)
 
Class IntegralClass
Line 2,652:
Delay( 500) ; Wait 1/2 sec
MessageRequester("Info", StrD(*a\Output())) ; Present the result
*a= FreeObject</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,659:
 
 
<langsyntaxhighlight lang=python>from time import time, sleep
from threading import Thread
 
Line 2,696:
ai.K = lambda t: 0
sleep(0.5)
print(ai.S)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang=racket>
#lang racket
 
Line 2,731:
(sleep/yield 0.5)
(displayln (send active output))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,738:
There is some jitter in the timer, but it is typically accurate to within a few thousandths of a second.
 
<langsyntaxhighlight lang=perl6>class Integrator {
has $.f is rw = sub ($t) { 0 };
has $.now is rw;
Line 2,782:
sleep .5;
 
say "f(0): ", $a.Output;</langsyntaxhighlight>
 
{{out|Typical output}}
Line 2,791:
=={{header|Rust}}==
 
<langsyntaxhighlight lang=rust>#![feature(mpsc_select)]
 
extern crate num;
Line 2,962:
thread::sleep(Duration::from_millis(100));
assert_eq!(object.output() as u32, 0)
}</langsyntaxhighlight>
 
=={{header|Scala}}==
 
<langsyntaxhighlight lang=Scala>object ActiveObject {
 
class Integrator {
Line 3,013:
integrator.bye
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang=Smalltalk>
Object subclass:#Integrator
instanceVariableNames:'tickRate input s thread'
Line 3,079:
showCR:(i stop).
].
</syntaxhighlight>
</lang>
running:
<syntaxhighlight lang =Smalltalk>Integrator example</langsyntaxhighlight>
 
output:
Line 3,104:
=={{header|SuperCollider}}==
Instead of writing a class, here we just use an environment to encapsulate state.
<langsyntaxhighlight lang=SuperCollider>
(
a = TaskProxy { |envir|
Line 3,136:
}
)
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang=Swift>// For NSObject, NSTimeInterval and NSThread
import Foundation
// For PI and sin
Line 3,204:
 
println(activeObject.Output())
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 3,214:
 
This implementation Tcl 8.6 for object support (for the active integrator object) and coroutine support (for the controller task). It could be rewritten to only use 8.5 plus the TclOO library.
<langsyntaxhighlight lang=Tcl>package require Tcl 8.6
oo::class create integrator {
variable e sum delay tBase t0 k0 aid
Line 3,263:
pause 0.5
puts [format %.15f [i output]]
}</langsyntaxhighlight>
Sample output:
-0.000000168952702
Line 3,271:
Since this object is CPU intensive, shutting it down when done is crucial. To facilitate this, the IDisposable pattern was used.
 
<langsyntaxhighlight lang=vbnet>Module Module1
Sub Main()
Line 3,344:
End Sub
End Class</langsyntaxhighlight>
 
 
Line 3,355:
 
What I've done instead is to pre-compute the number of updates performed on my machine for a given function and time period which is a fairly stable figure (though it will obviously be different on other machines). I've then used this figure to measure elapsed time for each update. On average this gives results of around 0.003 seconds which I consider acceptable in the circumstances.
<langsyntaxhighlight lang=ecmascript>import "scheduler" for Scheduler
import "timer" for Timer
 
Line 3,409:
 
integrator.stop()
System.print(integrator.output)</langsyntaxhighlight>
 
{{out}}
Line 3,419:
{{trans|Python}}
Uses cheese ball thread safety: since the integrator runs continuously and I don't want to queue the output, just sample it, strong references are used as they change atomically.
<langsyntaxhighlight lang=zkl>class Integrator{
// continuously integrate a function `K`, at each `interval` seconds'
fcn init(f,interval=1e-4){
Line 3,437:
fcn sample { S.value }
fcn setF(f) { K.set(f) }
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>ai:=Integrator(fcn(t){ ((0.0).pi*t).sin() });
Atomic.sleep(2);
ai.sample().println();
Line 3,444:
ai.setF(fcn{ 0 });
Atomic.sleep(0.5);
ai.sample().println();</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits