Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2024/25/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Templates

Select an element randomly.

(1) templates
import std.stdio;

T my_choice(T)(const T[] collection)
{
    import std.random : uniform;

    auto idx = uniform(0, collection.length); // [n, m) interval
    return collection[idx];
}

void main()
{
    int[] numbers = [8, 5, 1, 3];

    writeln(my_choice(numbers)); // 3
    writeln(my_choice(numbers)); // 5

    // ----------

    string[] words = ["aa", "bb", "cc", "dd"];

    writeln(my_choice(words)); // dd
    writeln(my_choice(words)); // cc
}

D has a choice() function, see here. This is just an example how it could be implemented manually.

Adding type constraints

Let's say we want to call my_choice() with string slices and int slices only. If the function is called with a different type, it should be a compile error.

(2) type constraints
import std.stdio;
import std.traits;  // from here

// here:                             vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
T my_choice(T)(const T[] collection) if (is(T == int) || is(T == string))
{
    import std.random : uniform;

    auto idx = uniform(0, collection.length); // [n, m) interval
    return collection[idx];
}

void main()
{
    int[] numbers = [8, 5, 1, 3];
    writeln(my_choice(numbers)); // OK

    // ----------

    string[] words = ["aa", "bb", "cc", "dd"];
    writeln(my_choice(words)); // OK

    // ----------

    double[] scores = [3.1, 2.6, 8.7];
    writeln(my_choice(scores)); // Error
}
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 June 29, 11:04