Active object: Difference between revisions
m
syntax highlighting fixup automation
(add FreeBASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 21:
=={{header|Ada}}==
<
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;</
Sample output:
<pre>
Line 93:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
INSTALL @lib$+"TIMERLIB"
INSTALL @lib$+"NOWAIT"
Line 115:
PROCwait(50)
PRINT "Final value = " FN(myinteg.output)
PROC_discard(myinteg{})</
Output:
<pre>
Line 125:
{{libheader|pthread}}
<
#include <stdlib.h>
#include <unistd.h>
Line 194:
return 0;
}</
output
<pre>-9.99348e-05</pre>
Line 200:
=={{header|C sharp|C#}}==
{{works with|C# 6}}
<
using System.Threading.Tasks;
Line 277:
Console.WriteLine(ao.Value);
}
}</
Output:
Line 284:
=={{header|C++}}==
{{works with|C++14|}}
<
#include <chrono>
#include <cmath>
Line 372:
std::this_thread::sleep_for(500ms);
std::cout << foo.output();
}</
output
<pre>1.23136e-011</pre>
=={{header|Clojure}}==
<
(:import (java.util Timer TimerTask)))
Line 413:
user> (test-integrator)
1.414065859052494E-5
</syntaxhighlight>
=={{header|Common Lisp}}==
{{libheader|Bordeaux Threads}}
<
(defclass integrator ()
((input :initarg :input :writer input :reader %input)
Line 502:
(format t "~F~%" (area integrator)))
(input nil integrator)))
</syntaxhighlight>
=={{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.
<
require "time"
Line 582:
proc_chan.send({Action::Finished, ->(t : Float64) { 0f64 }})
sleep 0.5.seconds
puts result_chan.receive</
Output:
Line 591:
=={{header|D}}==
{{trans|Java}}
<
import std.datetime;
import std.math;
Line 663:
v0 = v1;
}
}</
{{out}}
Line 671:
{{libheader| System.Classes}}
{{Trans|Python}}
<
program Active_object;
Line 757:
Integrator.Join;
Readln;
end.</
{{out}}
<pre>
Line 765:
=={{header|E}}==
<
var value := 0.0
var input := fn { 0.0 }
Line 815:
})
return result
}</
=={{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 ...
<
(require 'timer)
Line 850:
(else (error "active:bad message" message))))))
</syntaxhighlight>
{{Out}}
<
(define (experiment)
(define (K t) (sin (* PI t )))
Line 872:
3/7/2015 20:34:28 : result
result 0.00026510586971023164
</syntaxhighlight>
=={{header|Erlang}}==
I could not see what time to use between each integration so it is the argument to task().
<
-module( active_object ).
-export( [delete/1, input/2, new/0, output/1, task/1] ).
Line 939:
zero( _ ) -> 0.
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
open System.Threading
Line 984:
printfn "%f" (i.Output())
i.Stop()</
=={{header|Factor}}==
Working with dynamic quotations requires the stack effect to be known in advance. The apply-stack-effect serves this purpose.
<
math.constants math.functions prettyprint system threads ;
IN: rosettacode.active
Line 1,028:
0.5 seconds sleep
[ output . ] [ destroy ] bi ;
MAIN: active-test</
( 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:
<
#INCLUDE <Include\Windows.inc>
Line 1,127:
FUNCTION Task(BYVAL t AS DOUBLE) AS DOUBLE
RETURN SIN(2 * PI * 0.5 * t)
END FUNCTION</
'''Typical console output:'''
Line 1,134:
=={{header|FreeBASIC}}==
<
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>
{{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.
<
import (
Line 1,247:
time.Sleep(time.Second / 2) // 4. sleep .5 sec
fmt.Println(a.output()) // output should be near zero
}</
Output:
<pre>
Line 1,255:
=={{header|Groovy}}==
{{trans|Java}}
<
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
Line 1,324:
System.out.println(integrator.getOutput())
}
}</
{{out}}
<pre>0.0039642136156300455</pre>
Line 1,330:
=={{header|Haskell}}==
<
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 ()</
=={{header|J}}==
Line 1,412:
Implementation:
<
require'dates'
Line 1,435:
getoutput=:3 :0
Zero+G T''
)</
Task example (code):
<
delay=: 6!:3
Line 1,455:
delay 0.5
smoutput (T__object,getoutput__object) ''</
Task example (output):
Line 1,467:
=={{header|Java}}==
<
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
Line 1,537:
}
}
</syntaxhighlight>
Output:
<pre>4.783602720556498E-13</pre>
Line 1,545:
{{trans|E}}
<
var inputF = function () { return 0.0 };
var sum = 0.0;
Line 1,570:
shutdown: function () { clearInterval(updater) },
});
}</
Test program as a HTML fragment:
<
<script type="text/javascript">
Line 1,593:
}, 2000);
}, 1)
</script></
=={{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.
<
func::Function
runningsum::Float64
Line 1,638:
sleep(0.5)
v2 = it.runningsum
println("After 2.5 seconds, integrator value was $v2")</
=={{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.
<
import kotlin.math.*
Line 1,711:
integrator.stop()
println(integrator.getOutput())
}</
Sample output:
Line 1,720:
=={{header|Lingo}}==
Parent script "Integrator":
<
property _func
property _timeLast
Line 1,760:
me._timeLast = t
me._valueLast = val
end</
In some movie script:
<
-- entry point
Line 1,781:
put gIntegrator.output()
timer.forget()
end</
{{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).
<
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</
{{out}}
<pre>sampling interval: 0.500000, 6 updates over 2.5s total = -0.003628054395752
Line 1,839:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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]</
1.1309*10^-6
Line 1,968:
echo "Value after 0.5 more second: ", integrator.output()
integrator.destroy()
</syntaxhighlight>
{{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.
<
integrater = .integrater~new(.routines~sine) -- start the integrater function
call syssleep 2
Line 2,057:
::requires rxmath library
</syntaxhighlight>
=={{header|OxygenBasic}}==
Line 2,064:
With a high precision timer the result is around -.0002
<
double MainTime
Line 2,236:
print str(integral,4)
Rudolpho.clear</
=={{header|Oz}}==
<
fun {Const X}
fun {$ _} X end
Line 2,298:
{Show {I output($)}}
{I stop}</
=={{header|Perl}}==
<
use strict;
Line 2,369:
say "0 after .5 seconds: ", $x->output;
$x->delete;</
=={{header|Phix}}==
Line 2,375:
{{libheader|Phix/Class}}
<!--<
<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>
<!--</
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.
<!--<
<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>
<!--</
{{out}}
Line 2,534:
=={{header|PicoLisp}}==
<
(class +Active)
Line 2,577:
(wait 500) # Wait 0.5 sec
(prinl "Output: " (output> Obj)) # Print return value
(stop> Obj) ) ) # Stop active object</
=={{header|PureBasic}}==
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<
Class IntegralClass
Line 2,652:
Delay( 500) ; Wait 1/2 sec
MessageRequester("Info", StrD(*a\Output())) ; Present the result
*a= FreeObject</
=={{header|Python}}==
Line 2,659:
<
from threading import Thread
Line 2,696:
ai.K = lambda t: 0
sleep(0.5)
print(ai.S)</
=={{header|Racket}}==
<
#lang racket
Line 2,731:
(sleep/yield 0.5)
(displayln (send active output))
</syntaxhighlight>
=={{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.
<
has $.f is rw = sub ($t) { 0 };
has $.now is rw;
Line 2,782:
sleep .5;
say "f(0): ", $a.Output;</
{{out|Typical output}}
Line 2,791:
=={{header|Rust}}==
<
extern crate num;
Line 2,962:
thread::sleep(Duration::from_millis(100));
assert_eq!(object.output() as u32, 0)
}</
=={{header|Scala}}==
<
class Integrator {
Line 3,013:
integrator.bye
}
}</
=={{header|Smalltalk}}==
<
Object subclass:#Integrator
instanceVariableNames:'tickRate input s thread'
Line 3,079:
showCR:(i stop).
].
</syntaxhighlight>
running:
<syntaxhighlight lang
output:
Line 3,104:
=={{header|SuperCollider}}==
Instead of writing a class, here we just use an environment to encapsulate state.
<
(
a = TaskProxy { |envir|
Line 3,136:
}
)
</syntaxhighlight>
=={{header|Swift}}==
<
import Foundation
// For PI and sin
Line 3,204:
println(activeObject.Output())
</syntaxhighlight>
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.
<
oo::class create integrator {
variable e sum delay tBase t0 k0 aid
Line 3,263:
pause 0.5
puts [format %.15f [i output]]
}</
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.
<
Sub Main()
Line 3,344:
End Sub
End Class</
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.
<
import "timer" for Timer
Line 3,409:
integrator.stop()
System.print(integrator.output)</
{{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.
<
// 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) }
}</
<
Atomic.sleep(2);
ai.sample().println();
Line 3,444:
ai.setF(fcn{ 0 });
Atomic.sleep(0.5);
ai.sample().println();</
{{out}}
<pre>
|