This shows you the differences between two versions of the page.
dss:workshop-01 [2019/08/14 15:19] eduard.staniloiu [4. @safe] |
dss:workshop-01 [2021/03/10 23:46] (current) eduard.staniloiu |
||
---|---|---|---|
Line 1: | Line 1: | ||
====== Highschool workshop - Introduction to D ====== | ====== Highschool workshop - Introduction to D ====== | ||
+ | |||
+ | ===== Slides ===== | ||
+ | |||
+ | {{:dss:workshop-liceu.odp|Slides}} | ||
===== Exercises ===== | ===== Exercises ===== | ||
Line 61: | Line 65: | ||
==== 5. Function templates ==== | ==== 5. Function templates ==== | ||
- | <code D> | + | Write a simple templated function that computes the sum of the elements of an array. |
- | size_t numbersSum(T)(T[] numbers) | + | Your function should be able to work on any numeric type. This is exactly what we demoed in the presentation. |
- | { | + | |
- | size_t sum = 0; | + | |
- | foreach(num; numbers) | + | |
- | { | + | |
- | sum += num; | + | |
- | } | + | |
- | return sum; | + | |
- | } | + | |
- | + | ||
- | void main() | + | |
- | { | + | |
- | int[] arr = [1, 2, 3, 4, 5]; | + | |
- | writeln(numbersSum!int(arr)); // 15 | + | |
- | + | ||
- | float[] arr2 = [1.0, 2.0, 3.0, 4.0, 5.0]; | + | |
- | writeln(numbersSum!float(arr2)); // 15 | + | |
- | } | + | |
- | </code> | + | |
- | <code D> | + | <note> |
- | size_t numbersSum(T)(T[] numbers) | + | If you want to read more about D meta-programming, start with this introductory [[https://ocw.cs.pub.ro/courses/dss/laboratoare/02|hands-on]]. |
- | if (is(T == int) || is(T == float)) | + | </note> |
- | { | + | |
- | size_t sum = 0; | + | |
- | foreach(num; numbers) | + | |
- | { | + | |
- | sum += num; | + | |
- | } | + | |
- | return sum; | + | |
- | } | + | |
- | </code> | + | |
- | <code D> | ||
- | import std.traits : isNumeric; | ||
- | |||
- | size_t numbersSum(T)(T[] numbers) | ||
- | if (isNumeric!T) | ||
- | { | ||
- | size_t sum = 0; | ||
- | foreach(num; numbers) | ||
- | { | ||
- | sum += num; | ||
- | } | ||
- | return sum; | ||
- | } | ||
- | </code> |