How do I view the Ruby method #lcm in the source code? - ruby

I'm trying to understand how #lcm works. It belongs in the Integer class, as seen on the docs. I've looked at Ruby's github page but I don't know how to navigate it.
Thanks.

If you hover over a method in the Ruby docs you'll see "click to toggle source" on the right. Click on it and you'll see its definition:
VALUE
rb_lcm(VALUE self, VALUE other)
{
other = nurat_int_value(other);
return f_lcm(self, other);
}
This is C code, of course, rather than Ruby. Many of Ruby's core modules are implemented in C. For such modules I recommend another source of information: The Ruby Cross-Reference. There you can search for any C identifier, such as rb_lcm, and find its definition. In the case of Integer#lcm it's actually defined in rational.c (which you'll find in the root directory on GitHub). From there you can click on f_lcm to see its definition:
static VALUE
f_lcm(VALUE x, VALUE y)
{
if (f_zero_p(x) || f_zero_p(y))
return ZERO;
return f_abs(f_mul(f_div(x, f_gcd(x, y)), y));
}
...and so on.

Personally, I very much prefer to read Rubinius's source code over reading YARV's. Rubinius is much better structured, much better factored, and, above all, most of it is written in a language Ruby programmers know very well, namely Ruby:
def lcm(other)
raise TypeError, "Expected Integer but got #{other.class}" unless other.kind_of?(Integer)
if self.zero? or other.zero?
0
else
(self.div(self.gcd(other)) * other).abs
end
end
IronRuby's source code is also well structured, but unfortunately no longer really maintained:
[RubyMethod("lcm")]
public static object/*!*/ Lcm(int self, int other) {
return Lcm(self, other, SignedGcd(self, other));
}
[RubyMethod("lcm")]
public static object/*!*/ Lcm(BigInteger/*!*/ self, BigInteger/*!*/ other) {
return Lcm(self, other, SignedGcd(self, other));
}
[RubyMethod("lcm")]
public static object/*!*/ Lcm(object/*!*/ self, object other) {
throw RubyExceptions.CreateTypeError("not an integer");
}
My third choice would be JRuby:
public IRubyObject lcm(ThreadContext context, IRubyObject other) {
checkInteger(context, other);
return f_lcm(context, this, RubyRational.intValue(context, other));
}
Which points to this:
public static IRubyObject f_lcm(ThreadContext context, IRubyObject x, IRubyObject y) {
if (f_zero_p(context, x) || f_zero_p(context, y)) {
return RubyFixnum.zero(context.runtime);
}
return f_abs(context, f_mul(context, f_div(context, x, f_gcd(context, x, y)), y));
}

Related

Why is it possible initialize java.util.function.Consumer with lambda that returns value? [duplicate]

I am confused by the following code
class LambdaTest {
public static void main(String[] args) {
Consumer<String> lambda1 = s -> {};
Function<String, String> lambda2 = s -> s;
Consumer<String> lambda3 = LambdaTest::consume; // but s -> s doesn't work!
Function<String, String> lambda4 = LambdaTest::consume;
}
static String consume(String s) { return s;}
}
I would have expected the assignment of lambda3 to fail as my consume method does not match the accept method in the Consumer Interface - the return types are different, String vs. void.
Moreover, I always thought that there is a one-to-one relationship between Lambda expressions and method references but this is clearly not the case as my example shows.
Could somebody explain to me what is happening here?
As Brian Goetz pointed out in a comment, the basis for the design decision was to allow adapting a method to a functional interface the same way you can call the method, i.e. you can call every value returning method and ignore the returned value.
When it comes to lambda expressions, things get a bit more complicated. There are two forms of lambda expressions, (args) -> expression and (args) -> { statements* }.
Whether the second form is void compatible, depends on the question whether no code path attempts to return a value, e.g. () -> { return ""; } is not void compatible, but expression compatible, whereas () -> {} or () -> { return; } are void compatible. Note that () -> { for(;;); } and () -> { throw new RuntimeException(); } are both, void compatible and value compatible, as they don’t complete normally and there’s no return statement.
The form (arg) -> expression is value compatible if the expression evaluates to a value. But there are also expressions, which are statements at the same time. These expressions may have a side effect and therefore can be written as stand-alone statement for producing the side effect only, ignoring the produced result. Similarly, the form (arg) -> expression can be void compatible, if the expression is also a statement.
An expression of the form s -> s can’t be void compatible as s is not a statement, i.e. you can’t write s -> { s; } either. On the other hand s -> s.toString() can be void compatible, because method invocations are statements. Similarly, s -> i++ can be void compatible as increments can be used as a statement, so s -> { i++; } is valid too. Of course, i has to be a field for this to work, not a local variable.
The Java Language Specification §14.8. Expression Statements lists all expressions which may be used as statements. Besides the already mentioned method invocations and increment/ decrement operators, it names assignments and class instance creation expressions, so s -> foo=s and s -> new WhatEver(s) are void compatible too.
As a side note, the form (arg) -> methodReturningVoid(arg) is the only expression form that is not value compatible.
consume(String) method matches Consumer<String> interface, because it consumes a String - the fact that it returns a value is irrelevant, as - in this case - it is simply ignored. (Because the Consumer interface does not expect any return value at all).
It must have been a design choice and basically a utility: imagine how many methods would have to be refactored or duplicated to match needs of functional interfaces like Consumer or even the very common Runnable. (Note that you can pass any method that consumes no parameters as a Runnable to an Executor, for example.)
Even methods like java.util.List#add(Object) return a value: boolean. Being unable to pass such method references just because that they return something (that is mostly irrelevant in many cases) would be rather annoying.

Postconditions and TDD

One colleague in my team says that some methods should have both preconditions & postconditions. But the point is about code coverage, those conditions were not being called (not tested) until an invalid implementation implemented (just used in unit test). Lets take below example.
public interface ICalculator
{
int Calculate(int x, int y);
}
public int GetSummary(int x, int y)
{
// preconditions
var result = calculator.Calculate(x, y);
// postconditions
if (result < 0)
{
**throw new Exception("...");**
}
return result;
}
Two options for us:
1/ Remove test implementations + postconditions
2/ Keep both test implementations + postconditions
Can you give some advice please?
Keep pre- and post-conditions.
You'll need at least four tests here: combinations of (pre, post) x (pass, fail). Your failing post-condition test will pass if the expected exception is thrown.
This is easy to do in JUnit with its #Test(expected = Exception.class) annotation.
Be careful with colleagues that make blanket statements like "X must always be true." Dogma in all its forms should be avoided. Understand the reasons for doing things and do them when they make sense.
These conditions should be seen from design view. They ensure the calculator should be working fine, returning result in a range of expected values.
You should see the MS code contracts project to take a document there.

Benefit of defining success/failure function instead of using success/!success

I was reading man page of gearman code (http://manpages.ubuntu.com/manpages/precise/man3/gearman_success.3.html). They are having two functions
bool gearman_success(gearman_return_t rc)
bool gearman_failed(gearman_return_t rc)
And code of those functions look like (libgearman-1.0/return.h):
static inline bool gearman_failed(enum gearman_return_t rc)
{
return rc != GEARMAN_SUCCESS;
}
static inline bool gearman_success(enum gearman_return_t rc)
{
return rc == GEARMAN_SUCCESS;
}
Both function does nearly same thing. One return true and another false. What is the benefit of this code ?
Why not just have
!gearman_success
Is there benefit of coding pattern or something , which I am missing here.
This code is easier to extend. Suppose you add another value to that enum:
GEARMAN_SUCCESS_BUT_HAD_WARNINGS
With the implementation you're looking at, all you have to do is adjust both methods. Without it, you'd have to go through every place GEARMAN_SUCCESS is used all over the code base and make sure that the new enum value is handled properly.

Cheat sheet for all design patterns implemented in Ruby?

I wonder if there are cheat cheets for all design patterns implemented in Ruby so that you don't have to reinvent the wheel.
Design patterns are useful for organizing massive amounts of code. since you don't need to write as much code to do things in ruby as you do in #{verbose_algol_derivitive_language}, they don't have the same degree of importance.
What you will see used all the time is strategy and builder implemented with blocks (an example of builder would be form_for blocks in rails views, an example of strategy would be File.open) I can't really think of the last time I saw any others (gof patterns anyways)
EDIT: responding to
You mean with ruby we don't have to
think about design patterns in most
cases? Another question, if I'm using
Rails, do I actually have to think
about design patterns? Cause I don't
know where to use them. They don't
seem to fit in any component of the
MVC. Are design patterns only for
people that are building massive
libraries/frameworks eg. Rails,
DataMapper, MongoID etc and not for
others that only using these
frameworks/libraries?
For the most part, rails makes a lot of your decisions for you, and will until your app hits a fairly high level of complexity. Even if you are using something like sinatra though (which doesn't decide anything for you), you still won't really need to reach for those GoF patterns the same way as you would in a language like (for example) java.
This is because the whole point of design patterns is bottled ways to keep things flexible and maintainable. If that is built into the language, often they aren't even needed.
For example, a strategy pattern implemented in java looks sort of like this
//StrategyExample test application
class StrategyExample {
public static void main(String[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategySubtract's execute()");
return a - b; // Do a subtraction with a and b
}
}
class ConcreteStrategyMultiply implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyMultiply's execute()");
return a * b; // Do a multiplication with a and b
}
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
private Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
It is a lot of work, but what you end up with is worth it a lot of the time, and can be the difference between a big ball of mud, and something that has a chance in hell of being maintained. Now lets do it in ruby
class Context
def initialize(&strategy)
#strategy = strategy
end
def execute
#strategy.call
end
end
a = Context.new { puts 'Doing the task the normal way' }
a.execute #=> Doing the task the normal way
b = Context.new { puts 'Doing the task alternatively' }
b.execute #=> Doing the task alternatively
c = Context.new { puts 'Doing the task even more alternatively' }
c.execute #=> Doing the task even more alternatively
its hard to even call that a pattern, you are just using blocks! When the language covers the needs that the pattern addresses, effectively using the language will mean you don't really need the pattern in most circumstances. It also means you can elegantly address that kind of problem when it would be horrible overkill to do a java style strategy.
This document has nice examples of actual implementation of some of the design patterns from the GoF.
It may be a "cheatsheet", but I don't think is a silver-bullet reference for design patterns because they emerge once you have analyzed a problem, and the pattern fits the solution you're giving. Is not a recipe, but rather a good reference.
And, of course, is the great book Design patterns in Ruby

Why isn't .Except (LINQ) comparing things properly? (using IEquatable)

I have two collections of my own reference-type objects that I wrote my own IEquatable.Equals method for, and I want to be able to use LINQ methods on them.
So,
List<CandyType> candy = dataSource.GetListOfCandy();
List<CandyType> lollyPops = dataSource.GetListOfLollyPops();
var candyOtherThanLollyPops = candy.Except( lollyPops );
According to the documentation of .Except, not passing an IEqualityComparer should result in EqualityComparer.Default being used to compare objects. And the documentation for the Default comparer is this:
"The Default property checks whether type T implements the System.IEquatable generic interface and if so returns an EqualityComparer that uses that implementation. Otherwise it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T."
So, because I implement IEquatable for my object, it should use that and work. But, it doesn't. It doesn't work until I override GetHashCode. In fact, if I set a break point, my IEquatable.Equals method never gets executed. This makes me think that it's going with plan B according to its documentation. I understand that overriding GetHashCode is a good idea, anyway, and I can get this working, but I am upset that it is behaving in a way that isn't in line with what its own documentation stated.
Why isn't it doing what it said it would? Thank you.
After investigation, it turns out things aren't quite as bad as I thought. Basically, when everything is implemented properly (GetHashCode, etc.) the documentation is correct, and the behavior is correct. But, if you try to do something like implement IEquatable all by itself, then your Equals method will never get called (this seems to be due to GetHashCode not being implemented properly). So, while the documentation is technically wrong, it's only wrong in a fringe situation that you'd never ever want to do (if this investigation has taught me anything, it's that IEquatable is part of a whole set of methods you should implement atomically (by convention, not by rule, unfortunately)).
Good sources on this are:
Is there a complete IEquatable implementation reference?
MSDN Documentation: IEquatable<T>.Equals(T) Method
SYSK 158: IComparable<T> vs. IEquatable<T>
The interface IEqualityComparer<T> has these two methods:
bool Equals(T x, T y);
int GetHashCode(T obj);
A good implementation of this interface would thus implement both. The Linq extension method Except relies on the hash code in order to use a dictionary or set lookup internally to figure out which objects to skip, and thus requires that proper GetHashCode implementation.
Unfortunately, when you use EqualityComparer<T>.Default, that class does not provide a good GetHashCode implementation by itself, and relies on the object in question, the type T, to provide that part, when it detects that the object implements IEquatable<T>.
The problem here is that IEquatable<T> does not in fact declare GetHashCode so it's much easier to forget to implement that method properly, contrasted with the Equals method that it does declare.
So you have two choices:
Provide a proper IEqualityComparer<T> implementation that implements both Equals and GetHashCode
Make sure that in addition to implementing IEquatable<T> on your object, implement a proper GetHashCode as well
Hazarding a guess, are these different classes? I think by default IEquatable only works with the same class. So it might by falling back to the Object.Equal method.
I wrote a GenericEqualityComparer to be used on the fly for these types of methods: Distinct, Except, Intersect, etc.
Use as follows:
var results = list1.Except(list2, new GenericEqualityComparer<MYTYPE>((a, b) => a.Id == b.Id // OR SOME OTHER COMPARISON RESOLVING TO BOOLEAN));
Here's the class:
public class GenericEqualityComparer<T> : EqualityComparer<T>
{
public Func<T, int> HashCodeFunc { get; set; }
public Func<T, T, Boolean> EqualityFunc { get; set; }
public GenericEqualityComparer(Func<T, T, Boolean> equalityFunc)
{
EqualityFunc = equalityFunc;
HashCodeFunc = null;
}
public GenericEqualityComparer(Func<T, T, Boolean> equalityFunc, Func<T, int> hashCodeFunc) : this(equalityFunc)
{
HashCodeFunc = hashCodeFunc;
}
public override bool Equals(T x, T y)
{
return EqualityFunc(x, y);
}
public override int GetHashCode(T obj)
{
if (HashCodeFunc == null)
{
return 1;
}
else
{
return HashCodeFunc(obj);
}
}
}
I ran into this same problem, and debugging led me to a different answer than most. Most people point out that GetHashCode() must be implemented.
However, in my case - which was LINQ's SequenceEqual() - GetHashCode() was never called. And, despite the fact that every object involved was typed to a specific type T, the underlying problem was that SequenceEqual() called T.Equals(object other), which I had forgotten to implement, rather than calling the expected T.Equals(T other).

Resources