How can I avoid passing a lot of parameters into a nested function? - function

I have read that there is no way how to pass all outer local parameters to a nested function, but maybe there are some hacks to do it anyway? How can I avoid passing a lot of parameters into this function, for example:
let var1 = 5;
let var2 = 12.2;
let var3 = bar();
let var4 = tar() * var1;
// etc ... a lot of variables ...
fn foo() {
// want to have var1, var2, var3, var4 ...
}

What you want is called a closure:
fn main() {
let var1 = 5;
let var2 = 12.2;
let foo = || {
var1 as f64 + var2
};
println!("foo(): {}", foo()); // prints "foo(): 17.2"
}

Related

Writing a JSON of different types in Go (int and string)

I'm new to Go and Json, so I might miss a lot of points here.
So what I'm basically trying to do is making a program which performs the simple Fizz-Buzz program and make a JSON out of it.
This program takes two integers (a and b), iterate from a to b (i) and outputs:
"Fizz" if the number is a factor of 3
"Buzz" if the number is a factor of 5
"FizzBuzz" if the number is a factor both and,
i if the number isn't a factor of both
Using this simple code snippet:
func fizzbuzz(a int, b int) string{
str := fmt.Sprint("{\"output\":[")
for i := a ; i <= b; i++ {
if i%5 == 0 && i%3 == 0 {str = fmt.Sprint(str, "\"FizzBuzz\"")
}else if i%3 == 0 {str = fmt.Sprint(str, "\"Fizz\"")
}else if i%5 == 0 {str = fmt.Sprint(str, "\"Buzz\"")
}else {str = fmt.Sprint(str, i)}
str = str + ","
}
str = str[:len(str) - 1]
str = str + "]}"
return str
}
I was able to construct the string that can later on be converted to JSON:
{"output":["FizzBuzz",1,2,"Fizz",4,"Buzz","Fizz",7,8,"Fizz","Buzz",11,"Fizz",13,14,"FizzBuzz"]}
This works fine so far. I'm just wondering, are there any other solutions to making a JSON array of mixed type (integer and strings) on Golang? I've tried struct and marshaling, but a struct seems to have fixed structure.
There are two good options that come to mind.
You can use an interface type.
package main
import (
"encoding/json"
"os"
)
type output struct {
Output []interface{} `json:"output"`
}
func main() {
out := output{
Output: []interface{}{"FizzBuzz", 1, 2, "Fizz"},
}
d, _ := json.Marshal(out)
os.Stdout.Write(d)
}
Output:
{"output":["FizzBuzz",1,2,"Fizz"]}
Or you can use a different JSON library, like gojay, which has a different API for serializing JSON.

Ocaml - unexpected output

I have following code presented below:
let str = "AA";;
let i =ref 0;;
let tam_str = String.length str -1;;
let aux_char = 'A';;
let b_aux1 = ref false;;
exception Out_of_loop;;
try
while !i <= tam_str do
let c_r = str.[!i] in
if c_r = aux_char then(
b_aux1 := true;
i := !i +1;
)
else(
b_aux1 := false;
raise Out_of_loop
)
done;
with Out_of_loop ->();
if !b_aux1 then
print_endline "1"
else
print_endline "0";
;;
I expected the program to write the string "1" but it is returning "unit". But I don't understand why ... Can someone explain why?
Be careful of the precedence of the various constructs. You have written
try ...
with Out_of_loop ->
begin
();
if !b_aux1 then ...
end
while I suppose you wanted to write
begin
try ...
with Out_of_loop -> ()
end;
if !b_aux1 then ...

Parentheses around parameters in explicit F# constructor definition

When presented with the below four classes, my editor, VS2013, accepts the first three but gets confused by the fourth one.
type ClassOne =
val mutable myint: int
new (j) = { myint= j }
new () = ClassOne 1
type ClassTwo =
val mutable myint: int
new j = { myint= j }
new () = ClassTwo 2
type ClassThree =
val mutable myint: int
new j = { myint= j }
new () = ClassThree 3
type ClassFour =
val mutable myint: int
new j = { myint= j }
new () = ClassFour 4 // confusion here
My question is, in ClassFour when I use neither parentheses nor 'crooked' indentation for the constructor, what does the compiler think I am trying to do?

Function override

I found something interesting in Go. Let's say I have my package name is mypkg, inside mypkg, I have two functions:
package mypkg
func MyFunc0(){
//...
}
var MyFunc1 = func(){
//...
}
Now in my main package, it is possible to override MyFunc1, like this:
mypkg.MyFunc1 = func(){
// new logic
}
However, it is not possible to override MyFunc0 the same way. So now a question is raised. What are the differences between the two ways of declaring a function? Is this behavior difference intended?
MyFunc0 is a function declaration (https://golang.org/ref/spec#Function_declarations)
MyFunc1 is not a function declaration. It is a variable (https://golang.org/ref/spec#Variable_declarations) of type func (see https://golang.org/ref/spec#Function_types, https://golang.org/ref/spec#Function_literals). It has an initial value, but can be changed to hold a different value/function (as long as function signatures match).
I learning go language (and English :P), and in the tour of go is a exersie: Fibonacci closure
(https://tour.golang.org/moretypes/22)
The result is:
0
1
1
2
3
5
8
13
21
34
The main function is:
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
And my first solution was:
func fibonacci() func() int {
antant := 0
ant := 1
i := 0
return func() int {
var result int
if i == 0 || i == 1 {
result = i
i++
return result
}
result = antant + ant
antant = ant
ant = result
return result
}
}
But I didn't want ask in heach call to f() if was the firsth or second call (if i == 0 || i == 1). The result was a function auto-override:
type doFibonacci func(*doFibonacci) int
func fibonacci() func() int {
antant := 0
ant := 1
i := 0
doFibo := doFibonacci(func(ptrDo *doFibonacci) int {
var result int
if i == 0 || i == 1 {
result = i
i++
return result
}
*ptrDo = func(ptrDo *doFibonacci) int {
var result int
result = antant + ant
antant = ant
ant = result
return result
}
return (*ptrDo)(ptrDo)
})
return func() int {
return doFibo(&doFibo)
}
}
I apologize for my English.

Swift - Make the labels on constructor parameters optional?

Let's say, for instance, you have the following code:
struct SomeStruct {
init (arg1: String, arg2: Int){
// Does Stuff with Variables
}
}
// Some Point Later
var str = "fasfsad"
var integer = 343
let smth = SomeStruct(arg1: str, arg2: integer)
Is it possible to modify the SomeStruct struct to make the following line of code legal?
let smth = SomeStruct(str, integer)
Yes, you can make the parameters anonymous by using an underscore for the external parameter name:
struct SomeStruct {
init (_ arg1: String, _ arg2: Int){
// Does Stuff with Variables
}
}
Here is how you can do this:
struct A {
var a: String
var b: String
init(_ a: String,_ b: String) {
self.a = a
self.b = b
}
}
var x = A("S", "B")