vfmt: vfmt examples/*.v

pull/8935/head
Delyan Angelov 2021-02-23 19:43:44 +02:00
parent 0fa2f6d52c
commit 9e06af8bf9
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
18 changed files with 191 additions and 162 deletions

View File

@ -25,15 +25,23 @@ fn size(tree Tree) int {
// insert a value to BST // insert a value to BST
fn insert(tree Tree, x f64) Tree { fn insert(tree Tree, x f64) Tree {
match tree { match tree {
Empty { return Node{x, tree, tree} } Empty {
Node { return Node{x, tree, tree}
}
Node {
return if x == tree.value { return if x == tree.value {
tree tree
} else if x < tree.value { } else if x < tree.value {
Node{...tree, left: insert(tree.left, x)} Node{
...tree
left: insert(tree.left, x)
}
} else { } else {
Node{...tree, right: insert(tree.right, x)} Node{
} ...tree
right: insert(tree.right, x)
}
}
} }
} }
} }
@ -41,15 +49,17 @@ fn insert(tree Tree, x f64) Tree {
// whether able to find a value in BST // whether able to find a value in BST
fn search(tree Tree, x f64) bool { fn search(tree Tree, x f64) bool {
match tree { match tree {
Empty { return false } Empty {
Node { return false
}
Node {
return if x == tree.value { return if x == tree.value {
true true
} else if x < tree.value { } else if x < tree.value {
search(tree.left, x) search(tree.left, x)
} else { } else {
search(tree.right, x) search(tree.right, x)
} }
} }
} }
} }
@ -65,20 +75,46 @@ fn min(tree Tree) f64 {
// delete a value in BST (if nonexistant do nothing) // delete a value in BST (if nonexistant do nothing)
fn delete(tree Tree, x f64) Tree { fn delete(tree Tree, x f64) Tree {
match tree { match tree {
Empty { return tree } Empty {
return tree
}
Node { Node {
if tree.left is Node && tree.right is Node { if tree.left is Node && tree.right is Node {
return if x < tree.value { return if x < tree.value {
Node{...tree, left: delete(tree.left, x)} Node{
...tree
left: delete(tree.left, x)
}
} else if x > tree.value { } else if x > tree.value {
Node{...tree, right: delete(tree.right, x)} Node{
...tree
right: delete(tree.right, x)
}
} else { } else {
Node{...tree, value: min(tree.right), right: delete(tree.right, min(tree.right))} Node{
} ...tree
value: min(tree.right)
right: delete(tree.right, min(tree.right))
}
}
} else if tree.left is Node { } else if tree.left is Node {
return if x == tree.value { tree.left } else { Node{...tree, left: delete(tree.left, x)} } return if x == tree.value {
tree.left
} else {
Node{
...tree
left: delete(tree.left, x)
}
}
} else { } else {
if x == tree.value { return tree.right } else { return Node{...tree, right: delete(tree.right, x)} } if x == tree.value {
return tree.right
} else {
return Node{
...tree
right: delete(tree.right, x)
}
}
} }
} }
} }
@ -90,13 +126,13 @@ fn main() {
for i in input { for i in input {
tree = insert(tree, i) tree = insert(tree, i)
} }
println('[1] after insertion tree size is ${size(tree)}') // 11 println('[1] after insertion tree size is ${size(tree)}') // 11
del := [-0.3, 0.0, 0.3, 0.6, 1.0, 1.5] del := [-0.3, 0.0, 0.3, 0.6, 1.0, 1.5]
for i in del { for i in del {
tree = delete(tree, i) tree = delete(tree, i)
} }
print('[2] after deletion tree size is ${size(tree)}, ') // 7 print('[2] after deletion tree size is ${size(tree)}, ') // 7
print('and these elements were deleted: ') // 0.0 0.3 0.6 1.0 print('and these elements were deleted: ') // 0.0 0.3 0.6 1.0
for i in input { for i in input {
if !search(tree, i) { if !search(tree, i) {
print('$i ') print('$i ')

View File

@ -43,12 +43,8 @@ fn main() {
} }
fn greet_func(cmd Command) ? { fn greet_func(cmd Command) ? {
language := cmd.flags.get_string('language') or { language := cmd.flags.get_string('language') or { panic('Failed to get `language` flag: $err') }
panic('Failed to get `language` flag: $err') times := cmd.flags.get_int('times') or { panic('Failed to get `times` flag: $err') }
}
times := cmd.flags.get_int('times') or {
panic('Failed to get `times` flag: $err')
}
name := cmd.args[0] name := cmd.args[0]
for _ in 0 .. times { for _ in 0 .. times {
match language { match language {
@ -68,11 +64,9 @@ fn greet_func(cmd Command) ? {
} }
} }
} }
fun := cmd.flags.get_strings('fun') or { fun := cmd.flags.get_strings('fun') or { panic('Failed to get `fun` flag: $err') }
panic('Failed to get `fun` flag: $err')
}
for f in fun { for f in fun {
println('fun: ${f}') println('fun: $f')
} }
} }

View File

@ -2,12 +2,11 @@ import time
import net.http import net.http
fn main() { fn main() {
resp := http.get('https://vlang.io/utc_now') or { resp := http.get('https://vlang.io/utc_now') or {
println('failed to fetch data from the server') println('failed to fetch data from the server')
return return
} }
t := time.unix(resp.text.int()) t := time.unix(resp.text.int())
println(t.format()) println(t.format())
} }

View File

@ -1,5 +1,4 @@
// This program displays the fibonacci sequence // This program displays the fibonacci sequence
import os import os
fn main() { fn main() {
@ -10,7 +9,7 @@ fn main() {
// Exit // Exit
return return
} }
// Parse first argument and cast it to int // Parse first argument and cast it to int
stop := os.args[1].int() stop := os.args[1].int()
@ -25,7 +24,7 @@ fn main() {
mut b := u64(0) mut b := u64(0)
mut c := u64(1) mut c := u64(1)
for _ in 0..stop { for _ in 0 .. stop {
// Set a and b to the next term // Set a and b to the next term
a = b a = b
b = c b = c

View File

@ -9,8 +9,7 @@ fn main() {
} }
if s == '' { if s == '' {
println(n) println(n)
} } else {
else {
println(s) println(s)
} }
s = '' s = ''

View File

@ -1,8 +1,8 @@
import json import json
struct User { struct User {
name string name string
age int age int
mut: mut:
is_registered bool is_registered bool
} }

View File

@ -5,7 +5,7 @@ fn main() {
l.set_level(.info) l.set_level(.info)
// Make a new file called info.log in the current folder // Make a new file called info.log in the current folder
l.set_full_logpath('./info.log') l.set_full_logpath('./info.log')
println('Please check the file: ${l.output_file_name} after this example crashes.') println('Please check the file: $l.output_file_name after this example crashes.')
l.info('info') l.info('info')
l.warn('warn') l.warn('warn')

View File

@ -113,7 +113,7 @@ fn is_num_string(str string) bool {
fn main() { fn main() {
println('Please enter the expression you want to calculate, e.g. 1e2+(3-2.5)*6/1.5 .') println('Please enter the expression you want to calculate, e.g. 1e2+(3-2.5)*6/1.5 .')
println("Enter \'exit\' or \'EXIT\' to quit.") println("Enter 'exit' or 'EXIT' to quit.")
mut expr_count := 0 mut expr_count := 0
for { for {
expr_count++ expr_count++

View File

@ -2,127 +2,127 @@
// Output: // Output:
// -0.169075164 // -0.169075164
// -0.169059907 // -0.169059907
import math import math
const ( const (
solar_mass = 39.47841760435743197 //4.0 * math.Pi * math.Pi solar_mass = 39.47841760435743197 // 4.0 * math.Pi * math.Pi
days_per_year = 365.24 days_per_year = 365.24
c_n = 5 c_n = 5
) )
struct Position { struct Position {
pub mut: pub mut:
x f64 x f64
y f64 y f64
z f64 z f64
} }
struct Momentum { struct Momentum {
pub mut: pub mut:
x f64 x f64
y f64 y f64
z f64 z f64
m f64 m f64
} }
struct System { struct System {
pub mut: pub mut:
v []Momentum v []Momentum
s []Position s []Position
} }
fn advance(mut sys System, dt f64) { fn advance(mut sys System, dt f64) {
for i in 0..c_n - 1 { for i in 0 .. c_n - 1 {
mut vx := sys.v[i].x mut vx := sys.v[i].x
mut vy := sys.v[i].y mut vy := sys.v[i].y
mut vz := sys.v[i].z mut vz := sys.v[i].z
for j := i + 1; j < c_n; j++ { for j := i + 1; j < c_n; j++ {
dx := sys.s[i].x - sys.s[j].x dx := sys.s[i].x - sys.s[j].x
dy := sys.s[i].y - sys.s[j].y dy := sys.s[i].y - sys.s[j].y
dz := sys.s[i].z - sys.s[j].z dz := sys.s[i].z - sys.s[j].z
dsquared := dx * dx + dy * dy + dz * dz dsquared := dx * dx + dy * dy + dz * dz
distance := math.sqrt(dsquared) distance := math.sqrt(dsquared)
mag := (dt / (dsquared * distance)) mag := (dt / (dsquared * distance))
mi := sys.v[i].m mi := sys.v[i].m
vx -= dx * sys.v[j].m * mag vx -= dx * sys.v[j].m * mag
vy -= dy * sys.v[j].m * mag vy -= dy * sys.v[j].m * mag
vz -= dz * sys.v[j].m * mag vz -= dz * sys.v[j].m * mag
sys.v[j].x += dx * mi * mag sys.v[j].x += dx * mi * mag
sys.v[j].y += dy * mi * mag sys.v[j].y += dy * mi * mag
sys.v[j].z += dz * mi * mag sys.v[j].z += dz * mi * mag
} }
sys.v[i].x = vx sys.v[i].x = vx
sys.v[i].y = vy sys.v[i].y = vy
sys.v[i].z = vz sys.v[i].z = vz
} }
for i in 0..c_n { for i in 0 .. c_n {
sys.s[i].x += dt * sys.v[i].x sys.s[i].x += dt * sys.v[i].x
sys.s[i].y += dt * sys.v[i].y sys.s[i].y += dt * sys.v[i].y
sys.s[i].z += dt * sys.v[i].z sys.s[i].z += dt * sys.v[i].z
} }
} }
fn offsetmomentum(mut sys System) { fn offsetmomentum(mut sys System) {
mut px := f64(0) mut px := f64(0)
mut py := f64(0) mut py := f64(0)
mut pz := f64(0) mut pz := f64(0)
for i in 0..c_n { for i in 0 .. c_n {
px += sys.v[i].x * sys.v[i].m px += sys.v[i].x * sys.v[i].m
py += sys.v[i].y * sys.v[i].m py += sys.v[i].y * sys.v[i].m
pz += sys.v[i].z * sys.v[i].m pz += sys.v[i].z * sys.v[i].m
} }
sys.v[0].x = -px / solar_mass sys.v[0].x = -px / solar_mass
sys.v[0].y = -py / solar_mass sys.v[0].y = -py / solar_mass
sys.v[0].z = -pz / solar_mass sys.v[0].z = -pz / solar_mass
} }
fn energy(sys System) f64 { fn energy(sys System) f64 {
mut e := f64(0) mut e := f64(0)
for i in 0..c_n { for i in 0 .. c_n {
e += 0.5 * sys.v[i].m * (sys.v[i].x * sys.v[i].x + sys.v[i].y * sys.v[i].y + sys.v[i].z * sys.v[i].z) e += 0.5 * sys.v[i].m * (sys.v[i].x * sys.v[i].x + sys.v[i].y * sys.v[i].y +
for j := i + 1; j < c_n; j++ { sys.v[i].z * sys.v[i].z)
dx := sys.s[i].x - sys.s[j].x for j := i + 1; j < c_n; j++ {
dy := sys.s[i].y - sys.s[j].y dx := sys.s[i].x - sys.s[j].x
dz := sys.s[i].z - sys.s[j].z dy := sys.s[i].y - sys.s[j].y
distance := math.sqrt(dx * dx + dy * dy + dz * dz) dz := sys.s[i].z - sys.s[j].z
e -= (sys.v[i].m * sys.v[j].m) / distance distance := math.sqrt(dx * dx + dy * dy + dz * dz)
} e -= (sys.v[i].m * sys.v[j].m) / distance
} }
return e }
return e
} }
fn arr_momentum() []Momentum { fn arr_momentum() []Momentum {
return [ return [
Momentum {0.0, 0.0, 0.0, solar_mass}, Momentum{0.0, 0.0, 0.0, solar_mass},
Momentum {1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year, 9.54791938424326609e-04 * solar_mass}, Momentum{1.66007664274403694e-03 * days_per_year, 7.69901118419740425e-03 * days_per_year, -6.90460016972063023e-05 * days_per_year, 9.54791938424326609e-04 * solar_mass},
Momentum {-2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year, 2.85885980666130812e-04 * solar_mass}, Momentum{-2.76742510726862411e-03 * days_per_year, 4.99852801234917238e-03 * days_per_year, 2.30417297573763929e-05 * days_per_year, 2.85885980666130812e-04 * solar_mass},
Momentum {2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year, 4.36624404335156298e-05 * solar_mass}, Momentum{2.96460137564761618e-03 * days_per_year, 2.37847173959480950e-03 * days_per_year, -2.96589568540237556e-05 * days_per_year, 4.36624404335156298e-05 * solar_mass},
Momentum {2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year, 5.15138902046611451e-05 * solar_mass}, Momentum{2.68067772490389322e-03 * days_per_year, 1.62824170038242295e-03 * days_per_year, -9.51592254519715870e-05 * days_per_year, 5.15138902046611451e-05 * solar_mass},
] ]
} }
fn arr_position() []Position { fn arr_position() []Position {
return [ return [
Position {0.0, 0.0, 0.0}, Position{0.0, 0.0, 0.0},
Position {4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01}, Position{4.84143144246472090e+00, -1.16032004402742839e+00, -1.03622044471123109e-01},
Position {8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01}, Position{8.34336671824457987e+00, 4.12479856412430479e+00, -4.03523417114321381e-01},
Position {1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01}, Position{1.28943695621391310e+01, -1.51111514016986312e+01, -2.23307578892655734e-01},
Position {1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01}, Position{1.53796971148509165e+01, -2.59193146099879641e+01, 1.79258772950371181e-01},
] ]
} }
fn main() { fn main() {
mut sys := &System {arr_momentum(), arr_position()} mut sys := &System{arr_momentum(), arr_position()}
offsetmomentum(mut sys) offsetmomentum(mut sys)
println('${energy(sys):.9f}') //-0.169075164 println('${energy(sys):.9f}') //-0.169075164
for _ in 0..50_000_000 { for _ in 0 .. 50_000_000 {
advance(mut sys, 0.01) advance(mut sys, 0.01)
} }
println('${energy(sys):.9f}') //-0.169059907 println('${energy(sys):.9f}') //-0.169059907

View File

@ -1,5 +1,5 @@
import net import net
conn := net.dial_tcp('google.com:80')? conn := net.dial_tcp('google.com:80') ?
peer_addr := conn.peer_addr()? peer_addr := conn.peer_addr() ?
println('$peer_addr') println('$peer_addr')

View File

@ -3,21 +3,19 @@ import sync
import time import time
fn send_request(mut wg sync.WaitGroup) ?string { fn send_request(mut wg sync.WaitGroup) ?string {
start := time.ticks() start := time.ticks()
data := http.get('https://google.com')? data := http.get('https://google.com') ?
finish := time.ticks() finish := time.ticks()
println('Finish getting time ${finish - start} ms') println('Finish getting time ${finish - start} ms')
wg.done() wg.done()
return data.text return data.text
} }
fn main() { fn main() {
mut wg := sync.new_waitgroup() mut wg := sync.new_waitgroup()
for i := 0; i < 50; i++ { for i := 0; i < 50; i++ {
wg.add(1) wg.add(1)
go send_request(mut wg) go send_request(mut wg)
} }
wg.wait() wg.wait()
} }

View File

@ -474,8 +474,11 @@ fn radiance(r Ray, depthi int, scene_id int) Vec {
mut tmp := Vec{} mut tmp := Vec{}
if depth > 2 { if depth > 2 {
// Russian roulette // Russian roulette
tmp = if rand_f64() < pp { radiance(refl_ray, depth, scene_id).mult_s(rp) } else { radiance(Ray{x, tdir}, tmp = if rand_f64() < pp {
depth, scene_id).mult_s(tp) } radiance(refl_ray, depth, scene_id).mult_s(rp)
} else {
radiance(Ray{x, tdir}, depth, scene_id).mult_s(tp)
}
} else { } else {
tmp = (radiance(refl_ray, depth, scene_id).mult_s(re)) + tmp = (radiance(refl_ray, depth, scene_id).mult_s(re)) +
(radiance(Ray{x, tdir}, depth, scene_id).mult_s(tr)) (radiance(Ray{x, tdir}, depth, scene_id).mult_s(tr))

View File

@ -7,32 +7,34 @@ const (
fn main() { fn main() {
mut arr := []int{} mut arr := []int{}
for _ in 0..gen_len { for _ in 0 .. gen_len {
arr << rand.intn(gen_max) arr << rand.intn(gen_max)
} }
println('length of random array is $arr.len') println('length of random array is $arr.len')
println('before quick sort whether array is sorted: ${is_sorted<int>(arr)}') println('before quick sort whether array is sorted: ${is_sorted<int>(arr)}')
quick_sort<int>(mut arr, 0, arr.len-1) quick_sort<int>(mut arr, 0, arr.len - 1)
println('after quick sort whether array is sorted: ${is_sorted<int>(arr)}') println('after quick sort whether array is sorted: ${is_sorted<int>(arr)}')
} }
fn quick_sort<T>(mut arr []T, l int, r int) { fn quick_sort<T>(mut arr []T, l int, r int) {
if l>=r { return } if l >= r {
mut sep := l // what is sep: [...all_value<arr[sep]...sep...all_value>=arr[sep]...] return
for i in l+1..r+1 { }
mut sep := l // what is sep: [...all_value<arr[sep]...sep...all_value>=arr[sep]...]
for i in l + 1 .. r + 1 {
if arr[i] < arr[l] { if arr[i] < arr[l] {
sep++ sep++
arr[i], arr[sep] = arr[sep], arr[i] arr[i], arr[sep] = arr[sep], arr[i]
} }
} }
arr[l], arr[sep] = arr[sep], arr[l] arr[l], arr[sep] = arr[sep], arr[l]
quick_sort<T>(mut arr, l, sep-1) quick_sort<T>(mut arr, l, sep - 1)
quick_sort<T>(mut arr, sep+1, r) quick_sort<T>(mut arr, sep + 1, r)
} }
fn is_sorted<T>(arr []T) bool { fn is_sorted<T>(arr []T) bool {
for i in 0..arr.len-1 { for i in 0 .. arr.len - 1 {
if arr[i] > arr[i+1] { if arr[i] > arr[i + 1] {
return false return false
} }
} }

View File

@ -1,7 +1,7 @@
import rand import rand
fn main() { fn main() {
for _ in 0..10 { for _ in 0 .. 10 {
println('${rand.intn(255)}.${rand.intn(255)}.${rand.intn(255)}.${rand.intn(255)}') println('${rand.intn(255)}.${rand.intn(255)}.${rand.intn(255)}.${rand.intn(255)}')
} }
} }

View File

@ -14,10 +14,10 @@ fn main() {
fn sleeping_line(x int, y int, size int, ch string) { fn sleeping_line(x int, y int, size int, ch string) {
mut i := 0 mut i := 0
for i < size { for i < size {
term.set_cursor_position({ term.set_cursor_position(
x: x + i x: x + i
y: y y: y
}) )
print(term.bold(term.yellow(ch))) print(term.bold(term.yellow(ch)))
i++ i++
} }
@ -26,10 +26,10 @@ fn sleeping_line(x int, y int, size int, ch string) {
fn standing_line(x int, y int, size int, ch string) { fn standing_line(x int, y int, size int, ch string) {
mut i := 0 mut i := 0
for i < size { for i < size {
term.set_cursor_position({ term.set_cursor_position(
x: x x: x
y: y + i y: y + i
}) )
print(term.bold(term.yellow(ch))) print(term.bold(term.yellow(ch)))
i++ i++
} }

View File

@ -3,9 +3,7 @@ module main
import v.vmod import v.vmod
fn main() { fn main() {
mod := vmod.decode(@VMOD_FILE) or { mod := vmod.decode(@VMOD_FILE) or { panic('Error decoding v.mod') }
panic('Error decoding v.mod')
}
println('$mod.name has version $mod.version') println('$mod.name has version $mod.version')
println('\nThe full mod struct: \n$mod') println('\nThe full mod struct: \n$mod')
} }

View File

@ -10,7 +10,7 @@ fn main() {
for _ in 0 .. repeats { for _ in 0 .. repeats {
mut sb := strings.new_builder(blocksize) mut sb := strings.new_builder(blocksize)
for { for {
x := rand.read(blocksize)? x := rand.read(blocksize) ?
for c in x { for c in x {
if c >= `0` && c <= `~` { if c >= `0` && c <= `~` {
sb.write_b(c) sb.write_b(c)

View File

@ -12,6 +12,7 @@ import os
// https://wkhtmltopdf.org/libwkhtmltox/ // https://wkhtmltopdf.org/libwkhtmltox/
#flag -lwkhtmltox #flag -lwkhtmltox
#include "wkhtmltox/pdf.h" # You can install the C package for your system from the wkhtmltopdf.org/downloads.html page #include "wkhtmltox/pdf.h" # You can install the C package for your system from the wkhtmltopdf.org/downloads.html page
struct C.wkhtmltopdf_global_settings {} struct C.wkhtmltopdf_global_settings {}
struct C.wkhtmltopdf_object_settings {} struct C.wkhtmltopdf_object_settings {}