uniq-by

30分プログラム、その218List::MoreUtilsにないuniq_byを実装してみる。
本当はこれを実装した上で、昨日のYAML(id:mzp:20080107:collect)をマージするプログラムを書くつもりだったけど、これを書いただけで時間切れ。続きはまた明日。

使い方

uniq_by { $_[0] == $_[1] } 1,1,2,3,3; # -> 1,2,3

ソースコード

#! /usr/bin/perl
# -*- mode:perl; coding:utf-8 -*-
#
# uniq-by.pl -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/01/08 21:58:22
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

use strict;
use warnings;
use YAML;
use Data::Dumper;

sub uniq_by(&@);

sub uniq_by(&@){
    my ($f,@xs) = @_;

    return @xs if(@xs < 2);

    my ($x,$y,@ys) = @xs;
    if($f->($x,$y)){
	# $x equal $y
	uniq_by { $f->(@_) } $x,@ys;
    }else{
	$x,uniq_by { $f->(@_) } $y,@ys;
    }
}

my @xs = uniq_by { $_[0] == $_[1] } 1,1,2,3,3;
print Dumper(@xs);