Logo

Programming-Idioms

History of Idiom 5 > diff from v350 to v351

Edit summary for version 351 by :
Two fields on one line, +demo

Version 350

2015-11-18, 15:56:29

Version 351

2015-11-30, 12:37:24

Idiom #5 Create a 2D Point data structure

Declare a container type for two floating-point numbers x and y

Idiom #5 Create a 2D Point data structure

Declare a container type for two floating-point numbers x and y

Code
-module(points).
-export([new/2, x/1, y/1]).

-opaque point() :: #{x => float(), y => float()}.
-export_type([point/0]).

-spec new(float(), float()) -> point().
new(X, Y) -> #{x => X, y => Y}.

-spec x(point()) -> float().
x(#{x := X}) -> X.

-spec y(point()) -> float().
y(#{y := Y}) -> Y.
Code
-module(points).
-export([new/2, x/1, y/1]).

-opaque point() :: #{x => float(), y => float()}.
-export_type([point/0]).

-spec new(float(), float()) -> point().
new(X, Y) -> #{x => X, y => Y}.

-spec x(point()) -> float().
x(#{x := X}) -> X.

-spec y(point()) -> float().
y(#{y := Y}) -> Y.
Comments bubble
to use this module from somewhere else you do stuff like...
Point = points:new(X, Y),
X = points:x(Point),
Y = points:y(Point).
Comments bubble
to use this module from somewhere else you do stuff like...
Point = points:new(X, Y),
X = points:x(Point),
Y = points:y(Point).
Code
var p = { x: 1.122, y: 7.45 };
Code
var p = { x: 1.122, y: 7.45 };
Comments bubble
Types are implicit. Just initialize a variable.
Comments bubble
Types are implicit. Just initialize a variable.
Code
type Point struct {
    x, y float64
}
Code
type Point struct {
    x, y float64
}
Demo URL
http://play.golang.org/p/CkmxNoBejE
Demo URL
http://play.golang.org/p/CkmxNoBejE