Hilbert curve: Difference between revisions

→‎{{header|Fōrmulæ}}: Added L-system solution
(Added solution for Action!)
(→‎{{header|Fōrmulæ}}: Added L-system solution)
(38 intermediate revisions by 18 users not shown)
Line 8:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">T Point
x = 0
y = 0
Line 83:
L(line) lines
print(line)
print()</langsyntaxhighlight>
 
{{out}}
Line 139:
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<langsyntaxhighlight Actionlang="action!">DEFINE MAXSIZE="12"
 
INT ARRAY
Line 221:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Hilbert_curve.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|APDF}}
<syntaxhighlight lang="ada">with PDF_Out; use PDF_Out;
 
procedure Hilbert_Curve_PDF is
 
Length : constant := 500.0;
Corner : constant Point := (50.0, 300.0);
 
type Rule_Type is (A, B, C, D);
 
PDF : PDF_Out.Pdf_Out_File;
First : Boolean;
 
procedure Hilbert (Order : in Natural;
Rule : in Rule_Type;
Length : in Real;
X, Y : in Real)
is
L : constant Real := Length / 4.0;
begin
if Order = 0 then
if First then
First := False;
PDF.Move (Corner + (X, Y));
else
PDF.Line (Corner + (X, Y));
end if;
else
case Rule is
when A =>
Hilbert (Order - 1, D, 2.0 * L, X - L, Y + L);
Hilbert (Order - 1, A, 2.0 * L, X - L, Y - L);
Hilbert (Order - 1, A, 2.0 * L, X + L, Y - L);
Hilbert (Order - 1, B, 2.0 * L, X + L, Y + L);
when B =>
Hilbert (Order - 1, C, 2.0 * L, X + L, Y - L);
Hilbert (Order - 1, B, 2.0 * L, X - L, Y - L);
Hilbert (Order - 1, B, 2.0 * L, X - L, Y + L);
Hilbert (Order - 1, A, 2.0 * L, X + L, Y + L);
when C =>
Hilbert (Order - 1, B, 2.0 * L, X + L, Y - L);
Hilbert (Order - 1, C, 2.0 * L, X + L, Y + L);
Hilbert (Order - 1, C, 2.0 * L, X - L, Y + L);
Hilbert (Order - 1, D, 2.0 * L, X - L, Y - L);
when D =>
Hilbert (Order - 1, A, 2.0 * L, X - L, Y + L);
Hilbert (Order - 1, D, 2.0 * L, X + L, Y + L);
Hilbert (Order - 1, D, 2.0 * L, X + L, Y - L);
Hilbert (Order - 1, C, 2.0 * L, X - L, Y - L);
end case;
end if;
end Hilbert;
 
procedure Hilbert (Order : Natural; Color : Color_Type) is
begin
First := True;
PDF.Stroking_Color (Color);
Hilbert (Order, A, Length, Length / 2.0, Length / 2.0);
PDF.Finish_Path (Close_Path => False,
Rendering => Stroke,
Rule => Nonzero_Winding_Number);
end Hilbert;
 
begin
PDF.Create ("hilbert.pdf");
PDF.Page_Setup (A4_Portrait);
PDF.Line_Width (2.0);
 
PDF.Color (Black);
PDF.Draw (Corner + (0.0, 0.0, Length, Length), Fill);
 
Hilbert (6, Color => (0.9, 0.1, 0.8));
Hilbert (5, Color => (0.0, 0.9, 0.0));
 
PDF.Close;
end Hilbert_Curve_PDF;</syntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 234 ⟶ 312:
|}
 
<langsyntaxhighlight lang="algol68">BEGIN
INT level = 4; # <-- change this #
 
Line 290 ⟶ 368:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre> ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮
Line 328 ⟶ 406:
{{trans|Go}}
Requires [https://www.autohotkey.com/boards/viewtopic.php?t=6517 Gdip Library]
<langsyntaxhighlight AutoHotkeylang="autohotkey">gdip1()
HilbertX := A_ScreenWidth/2 - 100, HilbertY := A_ScreenHeight/2 - 100
Hilbert(HilbertX, HilbertY, 2**5, 5, 5, Arr:=[])
Line 393 ⟶ 471:
Gdip_Shutdown(pToken)
ExitApp
Return</langsyntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
As shown in https://www.ioccc.org/2012/tromp/hint.html, the 142+3 byte BLC program
 
<pre>0000000 18 18 18 18 11 11 54 68 06 04 15 5f f0 41 9d f9
0000020 de 16 ff fe 5f 3f ef f6 15 ff 94 68 40 58 11 7e
0000040 05 cb fe bc bf ee 86 cb 94 68 16 00 5c 0b fa cb
0000060 fb f7 1a 85 e0 5c f4 14 d5 fe 08 18 0b 04 8d 08
0000100 00 e0 78 01 64 45 ff e5 ff 7f ff fe 5f ff 2f c0
0000120 ee d9 7f 5b ff ff fb ff fc aa ff f7 81 7f fa df
0000140 76 69 54 68 06 01 57 f7 e1 60 5c 13 fe 80 b2 2c
0000160 18 58 1b fe 5c 10 42 ff 80 5d ee c0 6c 2c 0c 06
0000200 08 19 1a 00 16 7f bc bc fd f6 5f 7c 0a 20 31 32
0000220 33</pre>
 
(consisting of the 142 byte binary prefix https://github.com/tromp/AIT/blob/master/hilbert followed by "123") outputs the 3rd order Hilbert curve
 
<pre> _ _ _ _
| |_| | | |_| |
|_ _| |_ _|
_| |_____| |_
| ___ ___ |
|_| _| |_ |_|
_ |_ _| _
| |___| |___| |</pre>
 
=={{header|BQN}}==
{{trans|J}}
BQN does not have complex numbers as of the creation of this submission, so <code>Conj</code> and <code>CMul</code> implement complex number operations on two element arrays, for clarity's sake.
 
<syntaxhighlight lang="bqn">Conj←1‿¯1⊸×
Cmul←-´∘×⋈+´∘×⟜⌽
Iter←(⊢∾⟨1‿0⟩∾Conj¨∘⌽)∘(0‿¯1⊸CMul¨∘⌽∾⟨0‿¯1⟩∾⊢)
Plot←{•Plot´<˘⍉>+`⟨0‿0⟩∾Iter⍟𝕩 ⟨⟩}</syntaxhighlight>
 
This program is made for <code>•Plot</code> in the online implementation, and you can view the result in the [https://mlochbaum.github.io/BQN/try.html#code=Q29uauKGkDHigL/CrzHiirjDlwpDbXVs4oaQLcK04oiYw5fii4grwrTiiJjDl+KfnOKMvQpJdGVy4oaQKOKKouKIvuKfqDHigL8w4p+p4oi+Q29uasKo4oiY4oy9KeKImCgw4oC/wq8x4oq4Q011bMKo4oiY4oy94oi+4p+oMOKAv8KvMeKfqeKIvuKKoikKSGlsYmVydOKGkHvigKJQbG90wrQ8y5jijYk+K2Din6gw4oC/MOKfqeKIvkl0ZXLijZ/wnZWpIOKfqOKfqX0KIApIaWxiZXJ0IDU= Online REPL.]
 
=={{header|C}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define N 32
Line 467 ⟶ 582:
}
return 0;
}</langsyntaxhighlight>
{{output}}
<pre>Same as Kotlin entry.</pre>
Line 473 ⟶ 588:
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 589 ⟶ 704:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 665 ⟶ 780:
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 754 ⟶ 869:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 830 ⟶ 945:
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 944 ⟶ 1,059:
 
return lines;
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 1,017 ⟶ 1,132:
| __ | | __ | | __ | | __ | | __ | | __ | | __ | | __ |
|__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__|</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This is a very fancy version of the Hilbert curve. It allows you to draw multiple levels and you have the option of superimposing each level on top of the others. You can choose four different pen colors that alternate according to the level. The pen thickness can vary according to the level and can be increments or decremented according to the settings.
 
<syntaxhighlight lang="Delphi">
 
procedure ClearBackground(Image: TImage; Color: TColor);
{Clear image with specified color}
begin
Image.Canvas.Brush.Color:=Color;
Image.Canvas.Pen.Color:=Color;
Image.Canvas.Rectangle(Image.ClientRect);
end;
 
{Array of colors used in display}
 
type TColorArray = array of TColor;
 
{Option controls the size of lines for each level}
 
type TPenMode = (pmNormal,pmIncrement,pmDecrement);
 
{Combined structure controls the Hilbert display}
 
type TCurveOptions = record
Order: integer;
SuperImposed: boolean;
PenMode: TPenMode;
ColorArray: TColorArray;
end;
 
 
procedure DrawHillbertCurve(Canvas: TCanvas; Width,Height: integer; Options: TCurveOptions);
{ Hilbert Curve}
var X,Y,X0,Y0,H,H0,StartX,StartY: double;
var I,Inx: integer;
 
procedure LeftUpRight(I: integer); forward;
procedure DownRightUp(I: integer); forward;
procedure RightDownLeft(I: integer); forward;
procedure UpLeftDown(I: integer); forward;
 
 
procedure DrawRealLine(var X,Y: double);
begin
Canvas.LineTo(Trunc(X),Trunc(Y));
end;
 
procedure LeftUpRight(I: integer);
begin
if I>0 then
begin
UpLeftDown(I-1);
X:=X-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
X:=X+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
end;
end;
 
procedure DownRightUp(I: integer);
begin
if I>0 then
begin
RightDownLeft(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
X:=X+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
end;
end;
 
procedure RightDownLeft(I: integer);
begin
if I>0 then
begin
DownRightUp(I-1);
X:=X+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
X:=X-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
end;
end;
 
procedure UpLeftDown(I: integer);
begin
if I>0 then
begin
LeftUpRight(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
X:=X-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
end;
end;
 
begin
if Height<Width then H0:=Height else H0:=Width;
STARTX:=Width div 2;
STARTY:=Height div 2;
H:=H0;
X0:=STARTX;
Y0:=STARTY;
 
for I:=1 to Options.Order do
begin
case Options.PenMode of
pmDecrement: Canvas.Pen.Width:=(Options.Order - I) + 1;
pmIncrement: Canvas.Pen.Width:=I;
end;
Inx:=(I-1) mod Length(Options.ColorArray);
Canvas.Pen.Color:=Options.ColorArray[Inx];
H:=H / 2;
X0:=X0+(H / 2);
Y0:=Y0+(H / 2);
X:=X0;
Y:=Y0;
if not Options.SuperImposed and (Options.Order<>I) then continue;
Canvas.MoveTo(Trunc(X),Trunc(Y));
 
{ Draw Curve Of Order I }
LeftUpRight(I);
end;
end;
 
procedure ShowHilbertCurve(Image: TImage);
{Setup parameter and draw Hilbert curve on canvas}
var CA: TColorArray;
var Options: TCurveOptions;
begin
ClearBackground(Image,clWhite);
Image.Canvas.Pen.Width:=1;
SetLength(CA,4);
CA[0]:=clBlack;
CA[1]:=clGray;
CA[2]:=clSilver;
CA[3]:=clGray;
Options.Order:=5;
Options.SuperImposed:=True;
Options.PenMode:=pmNormal;
Options.ColorArray:=CA;
 
DrawHillbertCurve(Image.Canvas,Image.Width,Image.Height,Options);
end;
 
 
</syntaxhighlight>
{{out}}
[[File:DelphiHilbertCurve.png|thumb|none]]
<pre>
 
</pre>
 
=={{header|EasyLang}}==
 
{{trans|FutureBasic}}
 
[https://easylang.dev/show/#cod=jVBLDoIwEN33FG9JMSCtxp2HUajSpAFTUeH2zlAKRDa2TTPz5n2atr4yHmecjsLZxnxs1dU4aOzR8kQ8y4szNFdFETFkU5eENg2wFA/flqituxrfoccAd4dVsBo5cgHA3hgiM25ocWJ0ydBLsgp5MzbM2CTxpnv5hpvRcbSjq7JvaAaW+B1npzwcVnV4kiJru+XrhZ8EilyrtorAUvJXp/7S6ZUuZtMJDqzKRRQVtMOfUCW+ Run it]
 
<syntaxhighlight lang="easylang">
order = 64
linewidth 32 / order
scale = 100 / order - 100 / (order * order)
proc hilbert x y lg i1 i2 . .
if lg = 1
line (order - x) * scale (order - y) * scale
return
.
lg = lg div 2
hilbert x + i1 * lg y + i1 * lg lg i1 1 - i2
hilbert x + i2 * lg y + (1 - i2) * lg lg i1 i2
hilbert x + (1 - i1) * lg y + (1 - i1) * lg lg i1 i2
hilbert x + (1 - i2) * lg y + i2 * lg lg 1 - i1 i2
.
hilbert 0 0 order 0 0
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Hilbert curve. Nigel Galloway: September 18th., 2023
type C= |At|Cl|Ab|Cr
type D= |Z|U|D|L|R
let fD=function Z->0,0 |U->0,1 |D->0,-1 |L-> -1,0 |R->1,0
let fC=function At->[fD D;fD R;fD U] |Cl->[fD R;fD D;fD L] |Ab->[fD U;fD L;fD D] |Cr->[fD L;fD U;fD R]
let order(n,g)=match g with At->[n,Cl;D,At;R,At;U,Cr]
|Cl->[n,At;R,Cl;D,Cl;L,Ab]
|Ab->[n,Cr;U,Ab;L,Ab;D,Cl]
|Cr->[n,Ab;L,Cr;U,Cr;R,At]
let hilbert=Seq.unfold(fun n->Some(n,n|>List.collect order))[Z,At]
hilbert|>Seq.take 7|>Seq.iteri(fun n g->Chart.Line(g|>Seq.collect(fun(n,g)->(fD n)::(fC g))|>Seq.scan(fun(x,y)(n,g)->(x+n,y+g))(0,0))|>Chart.withTitle(sprintf "Hilbert order %d" n)|>Chart.show)
</syntaxhighlight>
{{out}}
[[File:Hilbert0.png]]
[[File:Hilbert1.png]]
[[File:Hilbert2.png]]
[[File:Hilbert3.png]]
[[File:Hilbert4.png]]
[[File:Hilbert5.png]]
[[File:Hilbert6.png]]
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-08-14}}
<langsyntaxhighlight lang="factor">USING: accessors L-system ui ;
 
: hilbert ( L-system -- L-system )
Line 1,031 ⟶ 1,367:
} >>rules ;
 
[ <L-system> hilbert "Hilbert curve" open-window ] with-ui</langsyntaxhighlight>
 
 
Line 1,066 ⟶ 1,402:
=={{header|Forth}}==
{{trans|Yabasic}}
{{works with|4tH |v3.62}}
<langsyntaxhighlight lang="forth">include lib/graphics.4th
 
64 constant /width \ hilbertHilbert curve order^2
9 constant /length \ length of a line
 
Line 1,098 ⟶ 1,434:
color_image 255 whiteout blue \ paint blue on white
0 dup origin! \ set point of origin
0 dup /width over dup hilbert \ hilbertHilbert curve, order=8
s" ghilbert.ppm" save_image \ save the image
</syntaxhighlight>
</lang>
Output:
''Since Rosetta Code doesn't seem to support uploads anymore, the resulting file cannot be shown.''
Line 1,106 ⟶ 1,442:
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">
Dim Shared As Integer ancho = 64
 
Line 1,125 ⟶ 1,461:
Hilbert(0, 0, ancho, 0, 0)
End
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Hilbert_curve}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
=== Recursive ===
In '''[https://formulae.org/?example=Hilbert_curve this]''' page you can see the program(s) related to this task and their results.
 
The following defines a function that creates a graphics of the Hilbert curve of a given order and size:
 
[[File:Fōrmulæ - Hilbert curve 01.png]]
 
'''Test cases'''
 
The following creates a table with Hilbert curves for orders 1 to 5:
 
[[File:Fōrmulæ - Hilbert curve 02.png]]
 
[[File:Fōrmulæ - Hilbert curve 03.png|279px]]
 
=== L-system ===
 
There are generic functions written in Fōrmulæ to compute an L-system in the page [[L-system#Fōrmulæ | L-system]].
 
The program that creates a Hilbert curve is:
 
[[File:Fōrmulæ - L-system - Hilbert curve 01.png]]
 
[[File:Fōrmulæ - L-system - Hilbert curve 02.png]]
 
=={{header|Frink}}==
This program generates arbitrary L-systems with slight modifications (see the commmented-out list of various angles and rules.)
<langsyntaxhighlight lang="frink">// General description:
// This code creates Lindenmayer rules via string manipulation
// It can generate many of the examples from the Wikipedia page
Line 1,251 ⟶ 1,609:
g.show[]
g.write["hilbert.png",512,undef]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
Hilbert Curve Order 64
<syntaxhighlight lang="futurebasic">
#define ORDER 64
 
_window = 1
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 651, 661 )
window _window, @"Order 64 Hilbert Curve In FutureBasic", r, NSWindowStyleMaskTitled
WindowSetBackgroundColor( _window, fn ColorBlack )
end fn
 
void local fn HilbertCurve( x as long, y as long, lg as long, i1 as long, i2 as long )
if ( lg == 1 )
line to ( ORDER-x ) * 10, ( ORDER-y ) * 10
exit fn
end if
lg = lg / 2
fn HilbertCurve( x+i1*lg, y+i1*lg, lg, i1, 1-i2 )
pen 2.0
fn HilbertCurve( x+i2*lg, y+(1-i2)*lg, lg, i1, i2 )
fn HilbertCurve( x+(1-i1)*lg, y+(1-i1)*lg, lg, i1, i2 )
fn HilbertCurve( x+(1-i2)*lg, y+i2*lg, lg, 1-i1, i2 )
end fn
 
fn BuildWindow
pen -2.0, fn ColorGreen
fn HilbertCurve( 0, 0, ORDER, 0, 0 )
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Hilbert_Curve_FutureBasic.png]]
 
=={{header|Go}}==
Line 1,258 ⟶ 1,650:
<br>
The following is based on the recursive algorithm and C code in [https://www.researchgate.net/profile/Christoph_Schierz2/publication/228982573_A_recursive_algorithm_for_the_generation_of_space-filling_curves/links/0912f505c2f419782c000000/A-recursive-algorithm-for-the-generation-of-space-filling-curves.pdf this paper]. The image produced is similar to the one linked to in the zkl example.
<langsyntaxhighlight lang="go">package main
 
import "github.com/fogleman/gg"
Line 1,292 ⟶ 1,684:
dc.Stroke()
dc.SavePNG("hilbert.png")
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,302 ⟶ 1,694:
and folded to a list of points in a square of given size.
 
<langsyntaxhighlight lang="haskell">import Data.BoolTree (boolTree (..))
 
import Data.Tree
---------------------- HILBERT CURVE ---------------------
 
hilbertTree :: Int -> Tree Char
hilbertTree n
| 0 < n = iterate go seed !! pred n
| otherwise = seed
where
seed = Node 'a' []
go tree
| null xs = Node c (flip Node [] <$> rule c)
| otherwise = Node c (go <$> xs)
where
c = rootLabel tree
xs = subForest tree
 
 
hilbertPoints :: Int -> Tree Char -> [(Int, Int)]
hilbertPoints w = go r (r, r)
where
r = quot w 2
go r xy tree
| null xs = centres
| otherwise = concat $ zipWith (go d) centres xs
where
d = quot r 2
f g x = g xy + (d * g x)
centres =
((,) . f fst)
<*> f snd <$> vectors (rootLabel tree)
xs = subForest tree
 
 
--------------------- PRODUCTION RULE --------------------
 
rule :: Char -> String
Line 1,322 ⟶ 1,747:
'd' -> [(-1, 1), (1, 1), (1, -1), (-1, -1)]
_ -> []
 
 
--------------------------- TEST -------------------------
 
main :: IO ()
Line 1,327 ⟶ 1,755:
let w = 1024
putStrLn $ svgFromPoints w $ hilbertPoints w (hilbertTree 6)
 
hilbertTree :: Int -> Tree Char
hilbertTree n =
let go tree =
let c = rootLabel tree
xs = subForest tree
in Node c (bool (go <$> xs) (flip Node [] <$> rule c) (null xs))
seed = Node 'a' []
in bool seed (iterate go seed !! pred n) (0 < n)
 
hilbertPoints :: Int -> Tree Char -> [(Int, Int)]
hilbertPoints w tree =
let go r xy tree =
let d = quot r 2
f g x = g xy + (d * g x)
centres = ((,) . f fst) <*> f snd <$> vectors (rootLabel tree)
xs = subForest tree
in bool (concat $ zipWith (go d) centres xs) centres (null xs)
r = quot w 2
in go r (r, r) tree
 
svgFromPoints :: Int -> [(Int, Int)] -> String
Line 1,352 ⟶ 1,760:
let sw = show w
points =
(unwords . fmap (((++<>) . show . fst) <*> ((' ' :) . show . snd))) xys
in unlines
[ "<svg xmlns=\"http://www.w3.org/2000/svg\"",
unwords
, unwords ["width=\"512\" height=\"512\" viewBox=\"5 5", sw, sw, "\"> "]
, ["width=\"512\"<path dheight=\"M512\" ++viewBox=\"5 points5", ++sw, sw, "\"> "],
, "stroke-width<path d=\"2\M" stroke=\++ points ++ "red\" fill=\"transparent\"/>",
"stroke-width=\"2\" stroke=\"red\" fill=\"transparent\"/>",
, "</svg>"
] "</langsvg>"
]</syntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Hilbert.bas"
110 OPTION ANGLE DEGREES
120 GRAPHICS HIRES 2
Line 1,379 ⟶ 1,788:
250 CALL HILBERT(S,N-1,-P)
260 PLOT LEFT 90*P;
270 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,385 ⟶ 1,794:
Note: J's {{ }} syntax requires a recent version of J (9.02 or more recent).
 
<langsyntaxhighlight Jlang="j">iter=: (, 1 , +@|.) @: (,~ 0j_1 ,~ 0j_1*|.)
hilbert=: {{0j1+(%{:) +/\0,iter ^: y ''}}
</syntaxhighlight>
 
For a graphical presentation, you could use (for example):
 
<syntaxhighlight lang="j">require'plot'
plot hilbert 5</syntaxhighlight>
 
For asciiart, you could instead use:
 
<syntaxhighlight lang="j">
asciiart=:{{
coords=. 1 3*"1 +. y % <./(,+.y)-.0
Line 1,398 ⟶ 1,816:
canvas=. '|' (>./"2 vertical#pairs)} canvas
}}
</lang>
 
For a graphical presentation, you could use (for example):
 
<lang J>require'plot'
plot hilbert 5</lang>
 
For asciiart, you could instead use:
 
<lang J> asciiart hilbert 4
__ __ __ __ __ __ __ __ __ __
|__ |__| __| |__ |__| __| |__ |__|
Line 1,423 ⟶ 1,833:
|__ |__| | |__| | |__| __| |__ |__|
__| __ |__ __| __ |__ __| __
|__ __| |__ __| |__ __| |__ __| |__ __| | </langsyntaxhighlight>
 
The idea is to represent the nth order hilbert curve as list of complex numbers that can be summed to trace the curve. The 0th order hilbert curve is an empty list. The first half of the n+1 the curve is formed by rotating the nth right by 90 degrees and reversing, appending -i and appending the nth curve. The whole n+1th curve is the first half appended to 1 appended to the conjugate of the reverse of the first half.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">// Translation from https://en.wikipedia.org/wiki/Hilbert_curve
 
import java.util.ArrayList;
Line 1,560 ⟶ 1,970:
return;
}
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 1,639 ⟶ 2,049:
 
An implementation of GO. Prints an SVG string that can be read in a browser.
<langsyntaxhighlight lang="javascript">const hilbert = (width, spacing, points) => (x, y, lg, i1, i2, f) => {
if (lg === 1) {
const px = (width - x) * spacing;
Line 1,692 ⟶ 2,102:
};
 
drawHilbert(6);</langsyntaxhighlight>
 
===Functional===
Line 1,703 ⟶ 2,113:
Like the version above, generates an SVG string for display in a browser.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ------------------ HILBERT CURVE ------------------
const main = () => {
 
// rulehilbertCurve :: Dict Char [Char(Int, Int)] ->
// Dict Char [Char] -> Int -> Int -> SVG string
const rule = {
const hilbertCurve = dictVector =>
a: ['d', 'a', 'a', 'b'],
dictRule => width => b: ['c', 'b', 'b', 'a'],compose(
c: ['b', 'c', 'c', 'd']svgFromPoints(width),
d: ['a'hilbertPoints(dictVector)(width), 'd', 'd', 'c']
hilbertTree(dictRule)
);
 
 
// hilbertTree :: Dict Char [Char] -> Int -> Tree Char
const hilbertTree = rule =>
n => {
const go = tree => {
const xs = tree.nest;
 
return Node(tree.root)(
0 < xs.length
? xs.map(go)
: rule[tree.root].map(
flip(Node)([])
)
);
};
const seed = Node("a")([]);
 
return 0 < n
? take(n)(
iterate(go)(seed)
)
.slice(-1)[0]
: seed;
};
 
 
// vectors :: Dict Char [(Int, Int)]
// hilbertPoints :: Size const-> vectorsTree =Char -> [({x, y)]
// hilbertPoints :: Int -> Tree Char 'a':-> [(Int, Int)]
const hilbertPoints = dict =>
w => tree => {
const go = d => (xy, t) => {
const
r = Math.floor(d / 2),
centres = dict[t.root]
.map(v => [
xy[0] + (r * v[0]),
xy[1] + (r * v[1])
]);
 
return 0 < t.nest.length
? zipWith(
go(r)
)(centres)(t.nest).flat()
: centres;
};
const d = Math.floor(w / 2);
 
return go(d)([d, d], tree);
};
 
 
// svgFromPoints :: Int -> [(Int, Int)] -> String
const svgFromPoints = w => xys => [
"<svg xmlns=\"http://www.w3.org/2000/svg\"",
`width="500" height="500" viewBox="5 5 ${w} ${w}">`,
`<path d="M${(xys).flat().join(" ")}" `,
// eslint-disable-next-line quotes
'stroke-width="2" stroke="red" fill="transparent"/>',
"</svg>"
].join("\n");
 
 
// -------------------- TEST ---------------------
const main = () =>
hilbertCurve({
"a": [
[-1, 1],
[-1, -1],
Line 1,724 ⟶ 2,198:
[1, 1]
],
'"b'": [
[1, -1],
[-1, -1],
Line 1,730 ⟶ 2,204:
[1, 1]
],
'"c'": [
[1, -1],
[1, 1],
Line 1,736 ⟶ 2,210:
[-1, -1]
],
'"d'": [
[-1, 1],
[1, 1],
Line 1,742 ⟶ 2,216:
[-1, -1]
]
});({
a: ["d", "a", "a", "b"],
b: ["c", "b", "b", "a"],
c: ["b", "c", "c", "d"],
d: ["a", "d", "d", "c"]
})(1024)(6);
 
// hilbertCurve :: Int -> SVG string
const hilbertCurve = n => {
const w = 1024
return svgFromPoints(w)(
hilbertPoints(w)(
hilbertTree(n)
)
);
}
 
// ---------------- GENERIC FUNCTIONS ----------------
// hilbertTree :: Int -> Tree Char
const hilbertTree = n => {
const go = tree =>
Node(
tree.root,
0 < tree.nest.length ? (
map(go, tree.nest)
) : map(x => Node(x, []), rule[tree.root])
);
const seed = Node('a', []);
return 0 < n ? (
take(n, iterate(go, seed)).slice(-1)[0]
) : seed;
};
 
// hilbertPointsNode :: Sizea -> [Tree Chara] -> [(x,Tree y)]a
const Node = v =>
// hilbertPoints :: Int -> Tree Char -> [(Int, Int)]
const// hilbertPointsConstructor =for wa =>Tree treenode =>which {connects a
// value of some constkind goto =a dlist =>of (xy,zero tree) => {or
// more child consttrees.
rxs => Math.floor(d / 2),{
type: centres = map("Node",
root: v => [,
nest: xs || xy[0] + (r * v[0]),
});
xy[1] + (r * v[1])
],
vectors[tree.root]
);
return 0 < tree.nest.length ? concat(
zipWith(go(r), centres, tree.nest)
) : centres;
};
const d = Math.floor(w / 2);
return go(d)([d, d], tree);
};
 
// svgFromPoints :: Int -> [(Int, Int)] -> String
const svgFromPoints = w => xys =>
['<svg xmlns="http://www.w3.org/2000/svg"',
`width="500" height="500" viewBox="5 5 ${w} ${w}">`,
`<path d="M${concat(xys).join(' ')}" `,
'stroke-width="2" stroke="red" fill="transparent"/>',
'</svg>'
].join('\n');
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
// TEST -------------------------------------------
const compose = (...fs) =>
console.log(
// A function defined by the right-to-left
hilbertCurve(6)
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
};
 
// GENERIC FUNCTIONS ----------------------------------
 
// Nodeflip :: (a -> [Treeb a]-> c) -> Treeb -> a -> c
const Nodeflip = (v, xs)op => ({
// The binary function type:op 'Node',with
// its arguments reversed.
root: v, // any type of value (consistent across tree)
nest:1 xs!== || []op.length
? (a, b) => op(b, a)
});
: (a => b => op(b)(a));
 
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
 
// iterate :: (a -> a) -> a -> Gen [a]
function*const iterate(f, x)= f {=>
let// vAn =infinite x;list of repeated applications
// of f, starting with the seed value x.
while (true) {
function* yield(vx); {
let v = f(v)x;
 
}
while (true) {
}
yield v;
v = f(v);
}
};
 
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
 
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
(Array.isArray(xs) || 'string' === typeof xs) ? (
// length. This enables xs.lengthzip and zipWith to choose
// the shorter argument when one is non-finite,
) : Infinity;
// like cycle, repeat etc
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
// The first n elements of a list,
'GeneratorFunction' !== xs.constructor.constructor.name ? (
// string of xs.slice(0characters, n)or stream.
)xs :=> [].concat.apply([],"GeneratorFunction" Array.from({!== xs
.constructor.constructor.name ? (
length: n
}, () => { xs.slice(0, n)
const) x: = xsArray.nextfrom();{
return x.done ? [] length: [x.value];n
}, ()); => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}).flat();
 
// Use of `take` and `length` here allows zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
constxs => ys => {
lng = Math.min(length(xs), length(ys)),const
as n = takeMath.min(lnglength(xs), xslength(ys)),
bs as = take(lng, ysn);(xs),
return Array.from bs = take(n)({ys);
 
length: lng
}, (_, i) => freturn Array.from(as[i], bs[i], i));{
length: n
};
}, (_, i) => f(as[i], bs[i]));
};
 
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The program given here generates SVG code that can be
viewed directly in a browser, at least if the file suffix is .svg.
 
See [[Peano_curve#Simple_Turtle_Graphics | Simple Turtle Graphics]]
for the simple-turtle.jq module used in this entry. The `include`
statement assumes the file is in the pwd.
<syntaxhighlight lang="jq">include "simple-turtle" {search: "."};
 
def rules:
{ A: "-BF+AFA+FB-",
B: "+AF-BFB-FA+" };
 
def hilbert($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("A"; "a") | gsub("B"; $rules["B"]) | gsub("a"; $rules["A"])
| p($count-1)
end;
"A" | p($count) ;
 
def interpret($x):
if $x == "+" then turtleRotate(90)
elif $x == "-" then turtleRotate(-90)
elif $x == "F" then turtleForward(5)
else .
end;
 
def hilbert_curve($n):
hilbert($n)
| split("")
| reduce .[] as $action (turtle([0,5]) | turtleDown;
interpret($action) ) ;
 
hilbert_curve(5)
| path("none"; "red"; 1) | svg(170)
</syntaxhighlight>
{{out}}
https://imgur.com/a/mJAaY6I
 
=={{header|Julia}}==
Color graphics version using the Gtk package.
<langsyntaxhighlight lang="julia">using Gtk, Graphics, Colors
 
Base.isless(p1::Vec2, p2::Vec2) = (p1.x == p2.x ? p1.y < p2.y : p1.x < p2.x)
Line 1,964 ⟶ 2,447:
signal_connect(endit, win, :destroy)
wait(cond)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 1,970 ⟶ 2,453:
 
The coordinates of the points are generated using a translation of the C code in the Wikipedia article and then scaled by a factor of 3 (n = 32).
<langsyntaxhighlight lang="scala">// Version 1.2.40
 
data class Point(var x: Int, var y: Int)
Line 2,035 ⟶ 2,518:
println()
}
}</langsyntaxhighlight>
 
{{output}}
Line 2,137 ⟶ 2,620:
The output is visible in [http://lambdaway.free.fr/lambdawalks/?view=hilbert Hibert curve]
 
<syntaxhighlight lang="scheme">
<lang Scheme>
1) two twinned recursive functions
 
Line 2,178 ⟶ 2,661:
{path {@ d="M {turtle 10 10 0 {H5}}" {stroke 1 #fff}}}
}
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Line 2,197 ⟶ 2,680:
* <num> repeat the following draw command <num> times
* <any> move on canvas without drawing
<langsyntaxhighlight lang="lua">-- any version from LuaJIT 2.0/5.1, Lua 5.2, Lua 5.3 to LuaJIT 2.1.0-beta3-readline
local bit=bit32 or bit -- Lua 5.2/5.3 compatibilty
-- Hilbert curve implemented by Lindenmayer system
Line 2,284 ⟶ 2,767:
local str=arg[2] or "A"
draw(str:hilbert(n))
</syntaxhighlight>
</lang>
{{output}} luajit hilbert.lua 4 1M9FAF-4F2+2F-2F-2F++4F-F-4F+2F+2F+2F++3F+2F+3F--4FA10F-16F-58F-16F-
<pre>
Line 2,309 ⟶ 2,792:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
'''Works with:''' Mathematica 11
<syntaxhighlight lang Mathematica="mathematica">Graphics@HilbertCurve[4]</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Algol68}}
<langsyntaxhighlight Nimlang="nim">const
Level = 4
Side = (1 shl Level) * 2 - 2
Line 2,420 ⟶ 2,903:
stdout.write(s)
stdout.writeLine("")
</syntaxhighlight>
</lang>
{{out}}
See Algol68 version.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use SVG;
use List::Util qw(max min);
 
Line 2,464 ⟶ 2,947:
open $fh, '>', 'hilbert_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh;</langsyntaxhighlight>
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/hilbert_curve.svg Hilbert curve] (offsite image)
 
Line 2,472 ⟶ 2,955:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/hilbert_curve.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\hilbert_curve.exw
Line 2,541 ⟶ 3,024:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Processing}}==
 
<langsyntaxhighlight lang="java">int iterations = 7;
float strokeLen = 600;
int angleDeg = 90;
Line 2,627 ⟶ 3,110:
yo += 25;
}
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">iterations = 7
stroke_len = 600
angle_deg = 90
Line 2,693 ⟶ 3,176:
yo -= 50
if keyCode == DOWN:
yo += 50</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,705 ⟶ 3,188:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight Pythonlang="python">'''Hilbert curve'''
 
from itertools import (chain, islice)
Line 2,847 ⟶ 3,330:
# TEST ---------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="python">
<lang Python>
import matplotlib.pyplot as plt
import numpy as np
Line 2,908 ⟶ 3,391:
tt.goto(tt.pos()[0] + item[0], tt.pos()[1] + item[1])
tt.done()
</syntaxhighlight>
</lang>
 
=={{header|QB64}}==
{{trans|YaBASIC}}
<langsyntaxhighlight lang="qb64">_Title "Hilbert Curve"
Dim Shared As Integer sw, sh, wide, cell
 
Line 2,940 ⟶ 3,423:
Call Hilbert(iX + (1 - p) * iL, iY + (1 - p) * iL, iL, p, q)
Call Hilbert(iX + (1 - q) * iL, iY + q * iL, iL, 1 - p, q)
End Sub</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 2,946 ⟶ 3,429:
Using an L-system.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "turtleduck.qky" loadfile ] now!
[ stack ] is switch.arg ( --> [ )
Line 2,976 ⟶ 3,459:
turtle
10 frames
witheach
[ switch
Line 2,981 ⟶ 3,465:
char L case [ -1 4 turn ]
char R case [ 1 4 turn ]
otherwise ( ignore ) ] ] </lang>
1 frames</syntaxhighlight>
 
{{output}}
 
[[File:Quackery Hilbert curve.png]]
https://imgur.com/pkEAauf
 
=={{header|Racket}}==
Line 2,991 ⟶ 3,476:
{{trans|Perl}}
 
<langsyntaxhighlight lang="racket">#lang racket
(require racket/draw)
Line 3,022 ⟶ 3,507:
target)
(make-curve 500 6 7 30 (make-color 255 255 0) (make-color 0 0 0))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 3,028 ⟶ 3,513:
{{works with|Rakudo|2018.03}}
 
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 3,056 ⟶ 3,541:
:polyline[ :points(@points.join: ','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/hilbert-perl6.svg Hilbert curve]
 
There is a variation of a Hilbert curve known as a [[wp:Moore curve|Moore curve]] which is essentially 4 Hilbert curves joined together in a loop.
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 3,088 ⟶ 3,573:
:polyline[ :points(@points.join: ','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/moore-perl6.svg Moore curve]
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Hilbert curve
 
Line 3,159 ⟶ 3,644:
x1 = x2
y1 = y2
</syntaxhighlight>
</lang>
Output image:
[https://www.dropbox.com/s/anwtxtrnqhubh4a/HilbertCurve.jpg?dl=0 Hilbert curve]
Line 3,168 ⟶ 3,653:
<br/>
Implemented as a Lindenmayer System, depends on JRuby or JRubyComplete
<syntaxhighlight lang="ruby">
<lang Ruby>
# frozen_string_literal: true
 
Line 3,244 ⟶ 3,729:
end
end
</syntaxhighlight>
</lang>
 
The grammar library:-
 
<langsyntaxhighlight lang="ruby">
# common library class for lsystems in JRubyArt
class Grammar
Line 3,271 ⟶ 3,756:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Output is a file in SVG format. Implemented using a Lindenmayer system as per the Wikipedia page.
<langsyntaxhighlight lang="rust">// [dependencies]
// svg = "0.8.0"
 
Line 3,357 ⟶ 3,842:
fn main() {
HilbertCurve::save("hilbert_curve.svg", 650, 6).unwrap();
}</langsyntaxhighlight>
 
{{out}}
[[Media:Hilbert_curve_rust.svg]]
See: [https://slack-files.com/T0CNUL56D-F016PFXV0SZ-e88b2585b5 hilbert_curve.svg] (offsite SVG image)
 
=={{header|Scala}}==
===[https://www.scala-js.org/ Scala.js]===
<langsyntaxhighlight Scalalang="scala">@js.annotation.JSExportTopLevel("ScalaFiddle")
object ScalaFiddle {
// $FiddleStart
Line 3,411 ⟶ 3,896:
}
// $FiddleEnd
}</langsyntaxhighlight>
{{Out}}Best seen running in your browser by [https://scalafiddle.io/sf/x7t2zdK/0 ScalaFiddle (ES aka JavaScript, non JVM)].
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
Line 3,497 ⟶ 3,982:
drawRight(x, y, 6);
readln(KEYBOARD);
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
Generic implementation of the Lindenmayer system:
<langsyntaxhighlight lang="ruby">require('Image::Magick')
 
class Turtle(
Line 3,608 ⟶ 4,093:
turtle.save_as(filename)
}
}</langsyntaxhighlight>
 
Generating the Hilbert curve:
<langsyntaxhighlight lang="ruby">var rules = Hash(
a => '-bF+aFa+Fb-',
b => '+aF-bFb-Fa+',
Line 3,628 ⟶ 4,113:
)
 
lsys.execute('a', 6, "hilbert_curve.png", rules)</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/hilbert-curve-sidef.png Hilbert curve]
 
Line 3,634 ⟶ 4,119:
{{libheader|Gtk+-3.0}}
 
<langsyntaxhighlight lang="vala">struct Point{
int x;
int y;
Line 3,764 ⟶ 4,249:
Gtk.main();
return 0;
}</langsyntaxhighlight>
 
=={{header|VBScript}}==
Again no graphics in VBScript, so I write SVG in a HTML file and I open it in the default browser.
A turtle graphics library makes the sub that draws the curve very simple
<syntaxhighlight lang="vb">
 
option explicit
'outputs turtle graphics to svg file and opens it
 
const pi180= 0.01745329251994329576923690768489 ' pi/180
const pi=3.1415926535897932384626433832795 'pi
class turtle
dim fso
dim fn
dim svg
dim iang 'radians
dim ori 'radians
dim incr
dim pdown
dim clr
dim x
dim y
 
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
 
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
 
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can't create svg file" :vscript.quit
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
 
sub hilb (n,a)
if n=0 then exit sub
x.rt a
hilb n-1,-a: x.fw 1:x.lt a: Hilb n - 1,a
x.fw 1
hilb n-1,a : x.lt a: x.fw 1: Hilb n - 1,-a
x.rt a
end sub
 
dim x
set x=new turtle
x.iangle=90
x.orient=0
x.incr=5
x.x=100:x.y=700
'star5
hilb 7,1
set x=nothing
</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|D}}
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Line 3,878 ⟶ 4,471:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 3,959 ⟶ 4,552:
{{trans|Go}}
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color, Point
import "dome" for Window
 
Line 3,996 ⟶ 4,589:
 
static draw(dt) {}
}</langsyntaxhighlight>
 
{{out}}
[[File:Wren-Hilbert_curve.png|400px]]
 
=={{header|XPL0}}==
Hilbert curve from turtle graphic program on Wikipedia.
<langsyntaxhighlight XPL0lang="xpl0">def Order=5, Size=15; \length of line segment
int Dir, X, Y;
 
Line 4,034 ⟶ 4,630:
Move(X, Y);
Hilbert(Order, 1);
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|Go}}
<langsyntaxhighlight Yabasiclang="yabasic">width = 64
sub hilbert(x, y, lg, i1, i2)
Line 4,054 ⟶ 4,650:
open window 655, 655
hilbert(0, 0, width, 0, 0)</langsyntaxhighlight>
 
=={{header|zkl}}==
Uses Image Magick and
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<langsyntaxhighlight lang="zkl">hilbert(6) : turtle(_);
 
fcn hilbert(n){ // Lindenmayer system --> Data of As & Bs
Line 4,085 ⟶ 4,681:
}
img.writeJPGFile("hilbert.zkl.jpg");
}</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/hilbert.zkl.jpg hilbert curve]
2,120

edits