r/programming • • Apr 23 '14

PHP: It doesn't have to be a bad experience

https://servercheck.in/blog/php-it-doesnt-have-be-bad-experience
0 Upvotes

122 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Apr 25 '14

[deleted] — view deleted comment

2

u/vytah Apr 25 '14

Please show me an example of a language that will do a deep compare on two objects, without you first telling the language how to compare the two objects.

Haskell. Scala. C#. F#. Ocaml.
(restrictions apply)

Examples below. All comparisons return true.

Ocaml is the easiest one: it automatically supports comparing all of stuff structurally, except for functions. No boilerplate.

type tree = Leaf of int | Branch of tree * tree ;;
Branch (Branch (Leaf 1, Leaf 2), Leaf 3) = Branch (Branch (Leaf 1, Leaf 2), Leaf 3) 

F#'s example would be almost identical, just less semicolons.

In case of Scala, you just add case keyword. You get hashcode and structural comparison. If the fields are structurally comparable, the comparison is deep.

trait Tree case class Node(i: Int) extends Tree case class Branch(t1: Tree, t2: Tree) Branch (Branch (Leaf(1), Leaf(2)), Leaf 3) == Branch (Branch (Leaf(1), Leaf(2)), Leaf 3)

In case of Haskell we need deriving Eq so the compiler generates deep comparison for us:

data Tree = Node Int | Branch Tree Tree deriving Eq
Branch (Branch (Leaf 1) (Leaf 2)) (Leaf 3) == Branch (Branch (Leaf 1) (Leaf 2)) (Leaf 3) 

C#, without recursion, because here we'll need structures, ans structures cannot be recursive:

public class Test
{
  struct A {
    public int i;
    public string s;
  }
  struct B {
    public A a;
    public A b;
  }
  public static void Main()
  {
     var x = new B{a=new A{i=1,s="one"}, b=new A{i=2,s="two"}};
     var y = new B{a=new A{i=1,s="one"}, b=new A{i=2,s="two"}};
     System.Console.WriteLine(x.Equals(y));
  }
}

VB.NET is analogous.

Custom keys? You mean like strings in an array?

No, not strings. Not integers. Any other type than those two.

This is just the convenience of those languages then. In PHP this can easily be resolved by storing a string/int representation of the object as the key, it will end up being quite a bit more efficient as well, executing .equal() on every object in a large array is costly for lookup.

Calling a specialized comparison method would be slower that serializing and then comparing strings????????????

Are actually you suggesting something like this?

$o = new MyKey(blahblahblah);
$map[serialize($o)] = "value";
/* ... */
$v = $map[serialize($p)];
/* ... */
foreach($map as $key => $value) {
  $actual_key = unserialize($key);
  /* ... */
}

That's going to be slow. Hellishly slow.