Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Solutions to Hamming's problem in Haskell & Perl.

1 view
Skip to first unread message

Kang-min Liu

unread,
Aug 16, 2022, 3:38:53 AM8/16/22
to

Hamming's problem 是要列舉出所有符合 2^i * 3^j * 5^k 這個形式的數字,其
中 i,j,k 皆為正整數或零。

Haskell[1] by ccshan:

hamming = 1 : foldl1 merge [ map (n*) hamming | n <- [2,3,5] ]
merge (x:xs) (y:ys) = case compare x y of
LT -> x : merge xs (y:ys)
GT -> y : merge (x:xs) ys
EQ -> x : merge xs ys

Perl [2] by mjd:

sub hamming {
my $href = \1; # Dummy reference
my $hamming = Stream->new(
1,
sub { &merge($$href->scale(2),
&merge($$href->scale(3),
$$href->scale(5))) });
$href = \$hamming; # Reference is no longer a dummy
$hamming;
}

sub merge {
my $s1 = shift;
my $s2 = shift;
return $s2 if $s1->is_empty;
return $s1 if $s2->is_empty;
my $h1 = $s1->head;
my $h2 = $s2->head;
if ($h1 > $h2) {
Stream->new($h2, sub { &merge($s1, $s2->tail) });
} elsif ($h1 < $h2) {
Stream->new($h1, sub { &merge($s1->tail, $s2) });
} else { # heads are equal
Stream->new($h1, sub { &merge($s1->tail, $s2->tail) });
}
}

[1]: http://conway.rutgers.edu/~ccshan/wiki/blog/posts/Hamming/
[2]: https://perl.plover.com/Stream/stream.html#hamming_solution
0 new messages