Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #264 Automated passing of array bounds

Pass a two-dimensional integer array a to a procedure foo and print the size of the array in each dimension. Do not pass the bounds manually. Call the procedure with a two-dimensional array.

foo :: [[a]] -> IO ()
foo a = print (length a, length $ head a)

main :: IO ()
main = foo [[1, 2, 3], [4, 5, 6]]
foo(List<List<int>> a) => print("${a.length} ${a[0].length}");
var a = [
    [1, 2],
    [3, 4],
    [5, 6]
  ];
foo(a);
module x
contains
  subroutine foo(a)
    integer, dimension(:,:) :: a
    print *,size(a,1), size(a,2)
  end subroutine foo
end module x

program main
  use x
  integer, dimension(5,10) :: a
  call foo(a)
end program main
int i = 0, m = a.length;
while (i < m) out.println(a[i++].length);
type
  T2DArray = array of array of Integer;

procedure foo(A: T2DArray);
begin
  writeln(Length(A),', ', Length(A[0]));
end;

var A: T2DArray;

begin
  A := T2DArray.Create([1,2,3],[1,2,3]);
  foo(A);  //prints 2, 3
end.
sub foo {
    my ($a) = @_;
    return scalar @{ $a }, scalar @{ $a->[0] };
}

my $a = [[1,2,3], [4,5,6]];
printf "%d %d\n", foo($a);
def foo(a):
    print(len(a), len(a[0]))
    return


a = [[1,2,3], [4,5,6]]
foo(a)
def foo(ar)
  puts "#{ar.size} #{ar.first.size}"
end

a = [[1,2,3], [4,5,6]]
foo(a)
fn foo(matrix: &[Vec<i32>]) {
    let iter = matrix.iter();
    let (vertical, _) = iter.size_hint();
    let horizontal = iter
        .max()
        .expect("empty array!")
        .len();
    println!("{horizontal} by {vertical}");
}

fn main() {
    let matrix = vec![
        vec![1, 2, 3],
        vec![4, 5, 6],
    ];
    foo(&matrix);
}
fn foo<const X: usize, const Y: usize>(_: [[i32;X];Y]) {
    println!("{} {}", Y, X);
}

let a = [
    [1, 2, 3],
    [4, 5, 6],
];
foo(a);

New implementation...
< >
tkoenig