This question already has answers here:
How to Use Infix (Comparison) operators as parameters in Go
(1 answer)
How to assign an operator to a variable in golang?
(2 answers)
Closed 9 months ago.
The goal
How can I get a built-in operator as a function?
I want to take advantage of functional programming.
I have some files with vectorizing functions (eg. Remap[inT any](sl []inT, f func(inT) inT)), which take a scalar function to apply on every element of one or two slices.
I know I could:
func eq(a, b int)bool{
return a==b
}
and hope that after inlining there'll be no overhead.
But I prefer a short, performant & consistent way, if exists.
In Python 3 I would:
int.__eq__
In Rust I would:
i32::eq
In C++ I would:
#include <functional>
/*code here*/
std::equal_to<int>()
How would you achieve this in Go?
How can I get built-in operator as a function? Any functional package in Go?
You cannot.
Related
This question already has answers here:
Dynamically initialize array size in go
(3 answers)
Closed 2 years ago.
I have recently started with golang and was working with arrays and came across a situation where I did not have the number of elements. Is there a way to initialize a array without a size and then append elements in the end? Something like there in other programming languages like c++, javascript where there are vectors and arrays that can be used and we can add elements by functions like push_back or push. Is there a way that we can do this or is there a library in which we can do this? Thank you!
a := []int{}
a = append(a, 4)
fmt.Println(a)
You can use slice for your purpose.
array := make([]int, 0)
array = append(array, 1)
array = append(array, 2)
Here, array is a slice of int type data and initially of size 0. You can append int type data by append(array, <int-type-data>).
With Golang, Arrays always have a fixed length:
In Go, an array is a numbered sequence of elements of a specific length.
(Source: https://gobyexample.com/arrays)
If you want the flexibility of a variable length, you'll probably want to use a Slice instead:
Slices are a key data type in Go, giving a more powerful interface to sequences than arrays.
(Source: https://gobyexample.com/slices)
This post on the go blog (though old) has a nice overview of the two data types.
This question already has answers here:
Is it possible to control the size of an array using the type parameter of a generic?
(2 answers)
Closed 6 years ago.
I'm trying to implement a B-Tree class for practice in Rust, which can be instantiated at various different values of b. I've tried the following code:
struct BTreeNode<T, b> {
vals: [Option<T>; b-1],
children: [Option<Box<BTreeNode<T, b>>>; b],
}
struct BTree<T, b> {
root: Option<BTreeNode<T, b>>,
}
but the compiler (reasonably) complains that
src/two_three_tree.rs:2:15: 2:16 error: unresolved name `b` [E0425]
src/two_three_tree.rs:2 vals: [Option<T>; b-1],
^
...
src/two_three_tree.rs:2:15: 2:16 error: array length constant evaluation error: non-constant path in constant expression [E0250]
src/two_three_tree.rs:2 vals: [Option<T>; b-1],
^
...
It looks like the B-Tree class in the standard library just uses a constant (which is a reasonable choice, since B-Trees are usually meant to take maximum advantage of caching; I'm just trying to do this in a more general way). Is this possible in the current version of Rust? If not, will it ever be possible?
(I'm imagining creating a 2-3 Tree of u32s by writing BTree<u32, 3>, or a 2-3-4 Tree of u32s by writing BTree<u32, 4>)
First of all, you're using b as a type, then as a value, the length of the array? I'm not sure what you want that to mean.
Second, the size of an array has to be known at compile time. Since you don't know the size of the array at compile-time, you might be better off using a Vector.
This question already has answers here:
Can't all or most cases of `each` be replaced with `map`?
(4 answers)
What is the difference between map, each, and collect? [duplicate]
(2 answers)
Closed 8 years ago.
If you want a method that collects an array without modifying it, you can use map, and you'll have something that works the same as each. For example, you could do this:
array.each do |x|
x += 10
print "#{x}"
end
but you could just as easily do this:
array.map{|x| print (x + 10).to_s}
and it would have the exact same result. While each can only do that, map can alter its function using the !, so I don't see why I would use each anymore. Could you explain why I should ever use each instead of map if map seems more versatile?
No. Use each for side-effects; use map for a (side-effect free) transformation.
While they both iterate the enumerable (at some point1), map collects the transformed results which should be used. To say map is a more powerful each is like saying a method that returns an unused value is more powerful than a method does not return a value - it's not of being more powerful, it's about using the correct tool.
Thus, while map can "do" what each does (by evaluation of supplied block), it does more and is useful for a different task: when the transformation, and not the side-effect, is desired. It is often considered poor practice to perform side-effects in a map (excluding, perhaps, the mutation of the mapped objects).
1Furthermore, map and each are not strictly interchangeable. In lazy vs. eager situations, a transformation like map can be lazy while each is only useful for side-effects and is never lazy. (It is not possible for each to be lazy because there is no resulting sequence to "observe" and force the evaluation later.)
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
What does # mean in LISP
I am learning lisp, but one thing I do not understand is why it is necessary for #' to be used. If a function with a specific name exists, why would lisp think its a variable?
Ex:
>(remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10))
(2 4 6 8 10)
Some lisps, like Common Lisp, require this. Others, like Scheme, do not.
You need to do this because the Lisp you're using has a separate namespace for functions versus "normal" variables. If you left out the #' then the symbol evenp would be interpreted as referring to the "normal" (non-function) namespace.
The read syntax
#'X
means exactly the same thing as
(FUNCTION X)
(FUNCTION X) means, roughly, "resolve the symbol X in the namespace of functions". Without this, X is evaluated as a variable. Functions and variables are in separate namespaces in Common Lisp. This is a rule.
As to the question, why would Lisp think it is a variable? Let's put it another way: given that there are two namespaces, why can't Lisp just fall back automatically on one or the other if there is no ambiguity? The reason is that that would be a hack compared to just Lisp-1 or Lisp-2, worse than either of them. Lisp-1 and Lisp-2 are words used in the Lisp culture to refer to dialects that have one a single namespace for variables and those that have two.
If you want to know more about the pros and cons of doing it one way or another, it's all in this paper by Kent Pitman and Richard Gabriel: http://www.nhplace.com/kent/Papers/Technical-Issues.html [Technical Issues of Separation in Function Cells and Value Cell].
As an aside: you can use 'FUNC or (QUOTE FUNC) instead: (remove-if-not 'evenp ...). This is a very late binding mechanism that goes through the symbol, and will not work for lexical functions. It probably won't compile very efficiently. Calling through 'FUNC always has to do a lookup through the symbol, whereas #'FUNC (at least in some important situations) can be optimized.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sort strings and numbers in Ruby
I have an array of place objects, each with a name (unique) and number (non-unique). Is there a simple way to use sort_by to first sort by number and then (within each number) by name?
I know I can write a custom block for sort, but if this is possible, it'd be even easier!
Not sure if this is what you mean by "custom block" but it seems pretty simple to me:
places.sort_by { |place| [place.number, place.name] }