2020年5月6日水曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 5(状態と振る舞い)、LESSON 23(組み立てと転送)の練習問題の解答を求めてみる。

コード

package main

import (
 "fmt"
 "math"
)

type coordinate struct {
 lat, long float64
}

func (c coordinate) description() string {
 return fmt.Sprintf("緯度%v, 経度%v", c.lat, c.long)
}

type location struct {
 name string
 coordinate
}

func (l location) description() string {
 return fmt.Sprintf("%v %v", l.name, l.coordinate.description())
}
func newLocation(name string, c coordinate) location {
 return location{name: name, coordinate: c}
}

type world struct {
 radius float64
}

func rad(f float64) float64 {
 return f * math.Pi / 180
}
func (w world) distance(p1, p2 location) float64 {
 s1, s2 := math.Sincos(rad(p1.lat))
 c1, c2 := math.Sincos(rad(p2.lat))
 clong := math.Cos(rad(p1.long - p2.long))
 return w.radius * math.Acos(s1*s2+c1*c2*clong)
}

type gps struct {
 current, destination location
 world
}

func (g gps) distance() float64 {
 return g.world.distance(g.current, g.destination)
}
func (g gps) message() string {
 return fmt.Sprintf("行き先(%v)まで%.2fkm",
  g.destination.description(), g.distance())
}

type rover struct {
 gps
}

func main() {
 mars := world{radius: 3389.5}
 brandburyLanding := newLocation(
  "Brandbury Landing",
  coordinate{lat: -4.5895, long: 137.4417},
 )
 elysiumPlanitia := newLocation(
  "Elysium Planitia",
  coordinate{lat: 4.5, long: 135.9},
 )
 marsGps := gps{
  current:     brandburyLanding,
  destination: elysiumPlanitia,
  world:       mars,
 }
 curiosity := rover{gps: marsGps}
 fmt.Println(curiosity.message())
}

入出力結果(Zsh、PowerShell、Terminal)

% go run gps.go
行き先(Elysium Planitia 緯度4.5, 経度135.9)まで5329.54km
%

0 コメント:

コメントを投稿