-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathissues.ts
More file actions
2445 lines (2268 loc) · 105 KB
/
Copy pathissues.ts
File metadata and controls
2445 lines (2268 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Issue } from './types'
const DOCS = 'https://mojolang.org/docs/manual'
/**
* Player-facing tickets for the MQ Robotics autonomy platform, sequenced to
* follow the Mojo Manual and grouped into numbered blocks by chapter:
*
* MQ-1xx Basics, Functions & entry point
* MQ-2xx Variables, Types, Literals & Collections
* MQ-3xx Operators & Control Flow
* MQ-4xx Errors & Context Managers
* MQ-5xx Structs & Modules
* MQ-6xx Value Ownership
* MQ-7xx Value Lifecycle
* MQ-8xx Metaprogramming (comptime, parameters, traits, generics,
* constraints, materialization, reflection)
* MQ-9xx Pointers, Low-Level Interop & Testing
*
* Play order is exactly the array order below. Priority encodes teaching tier:
* High = P1 core, Medium = P2 recommended, Low = P3 optional (Urgent = the very
* first "get it compiling" ticket). MQ Robotics builds autonomous mobile robots
* (AMRs), so scenarios are drawn from robot software.
*
* Each ticket ships a full, runnable (but broken or incomplete) Mojo program in
* `starter`. The player edits it and submits; the code is compiled AND executed
* on Compiler Explorer, and `validation` decides completion:
* - `run` → must compile, exit 0, and print exactly `expectedStdout`.
* - `source` → must compile + exit 0, and the code must match `patterns`
* (used for idioms that compile identically either way).
*
* Every starter and solution is verified against the live Mojo toolchain
* (mojo_1_0_0) via `npm run verify:exercises`.
*/
export const issues: Issue[] = [
{
id: 'MQ-101',
concept: "Every Mojo program must include a function named `main()` as the entry point",
title: 'Wire up the program entry point',
topic: 'Language Basics',
priority: 'Urgent',
docUrl: `${DOCS}/basics/#hello-world`,
dayDocUrls: [
{ label: 'Language basics', url: `${DOCS}/basics/` },
],
file: 'src/boot.mojo',
description:
'A Mojo executable starts at `main`. This file defines `boot()` but never ' +
'declares `main`, so there is no entry point and nothing runs. Add a `main` ' +
'that calls `boot()`.\n\n' +
'Example:\n```\ndef main():\n some_helper()\n```',
starter: `def boot():
print("MQ Robotics control daemon starting")
`,
validation: { kind: 'run', expectedStdout: 'MQ Robotics control daemon starting' },
hint: 'Add a `def main():` whose body calls `boot()`.',
},
{
id: 'MQ-102',
concept: "Code blocks such as functions, conditions, and loops are defined with a colon followed by indented lines",
title: 'Get the navigation stack booting',
topic: 'Language Basics',
priority: 'High',
docUrl: `${DOCS}/functions/#anatomy-of-a-function`,
file: 'src/nav.mojo',
description:
'A Mojo program runs from `main`. The boot message is sitting at column 0, ' +
'so it is not part of `main`\'s body — the file will not even compile. Mojo ' +
'uses 4-space indentation for code blocks. Indent it.\n\n' +
'Example:\n```\ndef main():\n print("some message")\n```',
starter: `def main():
print("MQ Robotics nav stack online")
`,
validation: { kind: 'run', expectedStdout: 'MQ Robotics nav stack online' },
hint: 'Put 4 spaces before the `print` so it lives inside `main`.',
},
{
id: 'MQ-103',
concept: "Mojo uses the `def` keyword to define functions",
title: 'Define the heartbeat function',
topic: 'Functions',
priority: 'High',
docUrl: `${DOCS}/functions/#anatomy-of-a-function`,
file: 'src/heartbeat.mojo',
description:
'The watchdog calls `heartbeat()`, but its definition is missing the `def` ' +
'keyword, so the file will not compile. Every function starts with `def`. ' +
'Add it.\n\n' +
'Example: `def some_function() -> String:`',
starter: `heartbeat() -> String:
return "heartbeat ok"
def main():
print(heartbeat())
`,
validation: { kind: 'run', expectedStdout: 'heartbeat ok' },
hint: 'A function definition must begin with `def`. Add it before `heartbeat`.',
},
{
id: 'MQ-104',
concept: "You must declare the type of each function parameter and argument; the return type follows `->`",
title: 'Annotate the occupancy-grid size helper',
topic: 'Functions',
priority: 'High',
docUrl: `${DOCS}/functions/#function-arguments`,
file: 'src/grid.mojo',
description:
"`grid_cells` multiplies an occupancy grid's rows and columns, but its " +
'arguments have no types, so the compiler rejects it. A type annotation ' +
'declares what kind of value a name holds, written `name: Type`; for a ' +
'function you annotate each argument and put the return type after `->`. ' +
'Annotate both arguments as `Int` and add the `Int` return type.\n\n' +
'Example: `def someFunction(a: Int, b: Int) -> Int:`',
starter: `def grid_cells(rows, cols):
return rows * cols
def main():
print("Grid cells:", grid_cells(3, 4))
`,
validation: { kind: 'run', expectedStdout: 'Grid cells: 12' },
hint: "A `def` won't compile with bare arguments. Give each argument an explicit type and declare the type the function returns — both are integers here.",
},
{
id: 'MQ-105',
concept: "Values are passed back using the `return` keyword; the return type is declared with the `-> type` syntax",
title: 'Implement the ring-buffer capacity helper',
topic: 'Functions',
priority: 'High',
docUrl: `${DOCS}/functions/#return-values`,
file: 'src/ring_buffer.mojo',
description:
'When a sensor ring buffer fills up, the ingest loop grows it by doubling ' +
'its capacity. A function hands a value back to its caller with the ' +
'`return` keyword, declaring the type it returns after `->`. ' +
'`grow_capacity` should return twice its input, but right now ' +
'it returns the value unchanged. Fix the body so `grow_capacity(21)` is ' +
'`42`.\n\n' +
'Example:\n```\ndef someFunction(x: Int) -> Int:\n return x + 1\n```',
starter: `# Ring-buffer helpers for the sensor ingest loop
def grow_capacity(n: Int) -> Int:
return n # TODO: should double the buffer's capacity
def main():
print("New capacity:", grow_capacity(21))
`,
validation: { kind: 'run', expectedStdout: 'New capacity: 42' },
hint: 'Right now the function hands back its input unchanged. Multiply it so the result is twice as large.',
},
{
id: 'MQ-106',
concept: "A docstring is a string literal in triple quotes placed as the first statement in a function body",
title: 'Document the command logger',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/`,
file: 'src/logging.mojo',
description:
'`log_command` has no documentation. A docstring is a string literal in ' +
'triple quotes placed as the first statement of a function body, where it ' +
'documents what the function does. Add a one-line docstring there using ' +
'triple quotes.\n\n' +
'Example: a short sentence summarizing the function, wrapped in triple quotes.',
starter: `def log_command(name: String) -> String:
return "Dispatching command: " + name
def main():
print(log_command("rotate-90"))
`,
validation: {
kind: 'source',
patterns: ['("""[\\s\\S]+?"""|\'\'\'[\\s\\S]+?\'\'\')'],
message: 'Add a triple-quoted docstring (""" … """ or \'\'\' … \'\'\') just below the function definition.',
},
hint: 'Put a short sentence describing the function on its very first body line, wrapped in triple quotes — Mojo treats that as the docstring.',
},
{
id: 'MQ-107',
concept: "Keyword arguments are specified using `argument_name = argument_value` and can be passed in any order",
title: 'Pass the speed limits by keyword',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/#keyword-arguments`,
file: 'src/limits_set.mojo',
description:
'`set_limits` takes `max_speed` then `max_accel`, but the call passes `5` ' +
'and `2` positionally — so the speed cap (should be 2) and accel cap (should ' +
'be 5) come out swapped. A keyword argument is passed as `name = value`, ' +
'which binds it to that argument by name regardless of position. Pass them ' +
'by keyword so each value lands in the argument you mean.\n\n' +
'Example: `some_fn(arg_name=value)`',
starter: `def set_limits(max_speed: Int, max_accel: Int):
print("speed:", max_speed, "accel:", max_accel)
def main():
set_limits(5, 2)
`,
validation: { kind: 'run', expectedStdout: 'speed: 2 accel: 5' },
hint: 'Name each argument at the call site (the `name=value` form) so each value lands in the argument you intend, regardless of order.',
},
{
id: 'MQ-108',
concept: "An optional argument includes a default value, and must appear after any required arguments",
title: 'Give the spin-up ramp a default',
topic: 'Functions',
priority: 'High',
docUrl: `${DOCS}/functions/#optional-arguments`,
file: 'src/spin_up.mojo',
description:
'The motor spin-up helper should take an optional ramp time, but `ramp_ms` ' +
'has no default, so calling `spin_up(900)` with a single argument will not ' +
'compile. An optional argument carries a default value and may be omitted ' +
'by the caller; it must come after any required arguments. Give `ramp_ms` a ' +
'default value of `100`.\n\n' +
'Example: `def some_fn(x: Int, y: Int = 0) -> Int:`',
starter: `def spin_up(rpm: Int, ramp_ms: Int) -> Int:
return rpm + ramp_ms
def main():
print("total:", spin_up(900))
`,
validation: { kind: 'run', expectedStdout: 'total: 1000' },
hint: 'Give the second argument a default value in the signature (assign it `100`). A one-argument call then fills it in automatically.',
},
{
id: 'MQ-109',
concept: "A single star (`*`) in the argument list marks the following arguments as keyword-only",
title: 'Pass the keyword-only diagnostic flag',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/#positional-only-and-keyword-only-arguments`,
file: 'src/diag.mojo',
description:
'`run_diagnostic` declares `verbose` after a bare `*`, which makes it ' +
'keyword-only — it cannot be passed positionally. The call supplies `True` ' +
'positionally, so it will not compile. Pass `verbose` by keyword.\n\n' +
'Example: `some_fn(arg, flag_name=value)`',
starter: `def run_diagnostic(name: String, *, verbose: Bool) -> String:
if verbose:
return name + " [verbose]"
return name
def main():
print(run_diagnostic("imu", True))
`,
validation: { kind: 'run', expectedStdout: 'imu [verbose]' },
hint: 'Everything after the bare `*` is keyword-only — supply that flag by name at the call site rather than positionally.',
},
{
id: 'MQ-110',
concept: "Use the variadic argument syntax `*argument_name` to accept a variable number of arguments",
title: 'Sum a variadic list of readings',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/#variadic-arguments`,
file: 'src/sum_readings.mojo',
description:
'`total` should accept any number of `Int` readings and add them up, but ' +
'`readings` is declared as a single `Int`, so `total(3, 4, 5)` will not ' +
'compile. A variadic argument, written `*name`, collects any number of ' +
'positional arguments into one iterable you can loop over. Make `readings` ' +
'a variadic argument with `*`.\n\n' +
'Example: `def some_fn(*values: Int) -> Int:`',
starter: `def total(readings: Int) -> Int:
var s = 0
for r in readings:
s += r
return s
def main():
print("sum:", total(3, 4, 5))
`,
validation: { kind: 'run', expectedStdout: 'sum: 12' },
hint: 'Prefix the argument with `*` so it collects all the positional arguments into one iterable you can loop over.',
},
{
id: 'MQ-111',
concept: "Use `pass` as a no-op placeholder when a block requires a body but has nothing to do",
title: 'Stub out the self-test routine',
topic: 'Functions',
priority: 'High',
docUrl: `${DOCS}/functions/#anatomy-of-a-function`,
file: 'src/self_test.mojo',
description:
'`run_self_test` is a stub that is not implemented yet, and its body is ' +
'empty. An empty block does not compile, because a ' +
'comment is not a statement. `pass` is a do-nothing placeholder that ' +
'satisfies the required indented block without performing any action. Give ' +
'the stub a body of `pass` so the file compiles and boot continues.\n\n' +
'Example:\n```\ndef todo():\n pass\n```',
starter: `def run_self_test():
# TODO: implement the real self-test later; this is just a stub
def main():
run_self_test()
print("self-test stub ran")
`,
validation: { kind: 'run', expectedStdout: 'self-test stub ran' },
hint: 'An indented block cannot be empty, and a comment does not count as a statement. Add the do-nothing placeholder statement (`pass`) as the function body so it compiles.',
},
{
id: 'MQ-113',
concept: "Implement separate versions of a function with different argument types to \"overload\" it",
title: 'Overload the footprint helper',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/#overloaded-functions`,
file: 'src/footprint.mojo',
description:
'`footprint` computes a square chassis footprint from one side, but the ' +
'fleet console also calls it with a width and a height — and that overload ' +
'does not exist yet, so the build fails. Overloading means defining several ' +
'functions with the same name but different argument types or counts; Mojo ' +
'picks the one that matches each call. Add a second `footprint` taking ' +
'`(w: Int, h: Int)` that returns `w * h`.\n\n' +
'Example: two `def`s with the same name but different argument lists.',
starter: `def footprint(side: Int) -> Int:
return side * side
def main():
print(footprint(4), footprint(2, 3))
`,
validation: { kind: 'run', expectedStdout: '16 6' },
hint: 'Mojo picks an overload by argument count/types. Add a second `def` with the same name but two `Int` arguments, alongside the existing one.',
},
{
id: 'MQ-115',
concept: "Functions are non-raising by default; add the `raises` keyword to propagate an error to the caller",
title: 'Propagate a raising sensor read',
topic: 'Functions',
priority: 'Medium',
docUrl: `${DOCS}/functions/#raising-and-non-raising-functions`,
file: 'src/sensor_read.mojo',
description:
'`read_sensor` is declared `raises`. `main` calls it but is not marked ' +
'`raises`, so the build fails — a non-raising function cannot call a raising ' +
'one without handling the error. Mark `main` as `raises`.\n\n' +
'Example: `def some_fn() raises:`',
starter: `def read_sensor(id: Int) raises -> Int:
if id < 0:
raise Error("bad sensor id")
return id * 10
def main():
print("reading:", read_sensor(2))
`,
validation: { kind: 'run', expectedStdout: 'reading: 20' },
hint: 'Add `raises` to `main`’s signature so it can propagate the error from `read_sensor`.',
},
{
id: 'MQ-201',
concept: "Explicitly-declared variables are created with the `var` keyword",
title: 'Declare the odometry tick counter with `var`',
topic: 'Variables',
priority: 'High',
docUrl: `${DOCS}/variables/#explicitly-declared-variables`,
dayDocUrls: [
{ label: 'Variables', url: `${DOCS}/variables/` },
{ label: 'Types', url: `${DOCS}/types/` },
],
file: 'src/odometry.mojo',
description:
'Our style guide requires explicit variable declarations. An ' +
'explicitly-declared variable is introduced with the `var` keyword. The ' +
'odometry tick counter is assigned without being declared. Declare it with ' +
'`var`.\n\n' +
'Example: `var someName = 0`',
starter: `def main():
tick_count = 0
tick_count += 1
print("Ticks processed:", tick_count)
`,
validation: {
kind: 'source',
patterns: ['\\bvar\\s+tick_count\\b'],
message: 'Declare `tick_count` explicitly with the `var` keyword.',
},
hint: "Without an explicit declaration keyword, the first assignment isn't a real variable definition. Add `var` to the line that first sets the counter.",
},
{
id: 'MQ-202',
concept: "Late initialization works only if the variable is declared with a type",
title: 'Annotate a late-initialized variable',
topic: 'Variables',
priority: 'High',
docUrl: `${DOCS}/variables/#explicitly-declared-variables`,
file: 'src/threshold.mojo',
description:
'This variable is declared on one line and assigned on the next — late ' +
'initialization, which works only when the declaration carries a type, ' +
'since there is no value yet for Mojo to infer one from. With a bare ' +
'`var threshold` the type is unknown, so the declaration is rejected. Give ' +
'it an explicit `Int` type annotation.\n\n' +
'Example: `var name: SomeType`',
starter: `def main():
var threshold
threshold = 10
print("threshold:", threshold)
`,
validation: { kind: 'run', expectedStdout: 'threshold: 10' },
hint: 'When a `var` has no initializer, Mojo can’t infer its type — give the declaration an explicit `Int` type annotation after the name.',
},
{
id: 'MQ-203',
concept: "Since variables are strongly typed, you can't assign a value of a different type",
title: 'Fix the sensor-count type mismatch',
topic: 'Variables',
priority: 'Medium',
docUrl: `${DOCS}/variables/#type-annotations`,
file: 'src/cast.mojo',
description:
'Mojo variables are strongly typed — a variable holds only values of its ' +
'declared type. This `Int` variable is initialized from a string literal ' +
'`"5"`, and Mojo will not implicitly convert a string to an integer, so it ' +
'fails to compile with:\n\n' +
'```\n' +
'error: cannot implicitly convert \'StringLiteral["5"]\' value to \'Int\'\n' +
'```\n\n' +
'Assign an integer literal instead.\n\n' +
'Example: `var n: Int = 5`',
starter: `def main():
var count: Int = "5"
print("count:", count)
`,
validation: { kind: 'run', expectedStdout: 'count: 5' },
hint: 'Replace the quoted `"5"` with the integer `5` — the value must match the declared `Int` type.',
},
{
id: 'MQ-207',
concept: "A variable owns its value; ownership is transferred with the `^` sigil, which leaves the source uninitialized",
title: 'Keep the original after handing one off',
topic: 'Value Semantics',
priority: 'Low',
docUrl: `${DOCS}/variables/#variable-semantics`,
file: 'src/copy_move.mojo',
description:
'The starter transfers `a` into `b` with the `^` move operator, which ' +
'consumes `a` — so the later `a.append(4)` uses a value that no longer ' +
'exists and the build fails. We need both lists, so make an explicit copy ' +
'instead of moving.\n\n' +
'Example: `var b = original.copy()` copies; `var b = original^` moves (consumes the original).',
starter: `def main():
var a: List[Int] = [1, 2, 3]
var b = a^
a.append(4)
print("a:", len(a), "b:", len(b))
`,
validation: { kind: 'run', expectedStdout: 'a: 4 b: 3' },
hint: 'The `^` hands ownership away, leaving the original consumed. Mojo wants copies to be explicit, so ask the list for one with its `.copy()` method instead of moving it.',
},
{
id: 'MQ-208',
concept: "Use the `ref name` syntax to bind a reference to a value rather than an owned copy",
title: 'Bind a mutable reference into the buffer',
topic: 'Value Semantics',
priority: 'Low',
docUrl: `${DOCS}/values/lifetimes/`,
file: 'src/ref_bind.mojo',
description:
'Writing through `first` should change the first reading in place, but ' +
'`var first = readings[0]` binds a *copy*, so the write never reaches the ' +
'list and it still prints 10. The `ref name = expr` syntax binds a ' +
'reference — an alias to an existing value rather than an owned copy — so ' +
'writes reach the original. Bind a reference with `ref` instead.\n\n' +
'Example: `ref name = container[index]`',
starter: `def main():
var readings: List[Int] = [10, 20, 30]
var first = readings[0]
first = 99
print("first:", readings[0])
`,
validation: { kind: 'run', expectedStdout: 'first: 99' },
hint: 'Bind the name with `ref` instead of `var` so it aliases the list element in place rather than copying it out.',
},
{
id: 'MQ-210',
concept: "Numeric operators don't automatically narrow or widen operands to a common type",
title: 'Add across two integer widths',
topic: 'Types',
priority: 'Medium',
docUrl: `${DOCS}/types/#numeric-type-conversion`,
file: 'src/numeric_types.mojo',
description:
'`widen_add` adds an `Int8` reading to an `Int64` running total, but Mojo ' +
'will not implicitly mix the two widths, so the add does not compile. ' +
'Convert the `Int8` to `Int64` before adding.\n\n' +
'Example: `Int64(someInt8) + someInt64`',
starter: `def widen_add(reading: Int8, total: Int64) -> Int64:
return reading + total
def main():
print("total:", widen_add(100, 1000))
`,
validation: { kind: 'run', expectedStdout: 'total: 1100' },
hint: 'Widen the narrow value to `Int64` before the addition so both operands share the same type.',
},
{
id: 'MQ-211',
concept: "Convert the operands to the target type's constructor before dividing to avoid integer truncation",
title: 'Stop truncating the average loop latency',
topic: 'Types',
priority: 'High',
docUrl: `${DOCS}/types/#numeric-type-conversion`,
file: 'src/latency.mojo',
description:
'Average control-loop latency should be `3.5`, but dividing two `Int`s does ' +
'integer division and discards the fraction before the result becomes a ' +
'`Float64`. Convert the operands to floating point before dividing.\n\n' +
'Example: `Float64(someInt) / Float64(otherInt)`',
starter: `def avg_latency(total_ms: Int, num_loops: Int) -> Float64:
return total_ms / num_loops
def main():
print("avg latency:", avg_latency(7, 2))
`,
validation: { kind: 'run', expectedStdout: 'avg latency: 3.5' },
hint: 'Dividing two whole numbers happens in integer space and drops the remainder before the value is ever widened to a float, so 7 over 2 loses its .5. Convert each operand to a floating-point type first, then divide.',
},
{
id: 'MQ-213',
concept: "A `SIMD` value is a fixed-size vector defined by two parameters: a `DType` and the number of elements",
title: 'Define the velocity vector type',
topic: 'SIMD & DType',
priority: 'High',
docUrl: `${DOCS}/types/#simd-and-dtype`,
file: 'src/velocity.mojo',
description:
'`main` uses a `Velocity` type that does not exist yet. A `SIMD` value is a ' +
'fixed-size vector defined by two parameters: a `DType` (its element type) ' +
'and the number of lanes. Define a `comptime` type alias named `Velocity` ' +
'for a 4-lane float32 SIMD vector at the top of the file.\n\n' +
'Example: `comptime SomeVector = SIMD[DType.float64, 8]`',
starter: `def main():
var v = Velocity(1.0, 2.0, 3.0, 4.0)
print("Velocity lane 0:", v[0])
`,
validation: { kind: 'run', expectedStdout: 'Velocity lane 0: 1.0' },
hint: 'The name `Velocity` is undefined until you create it. Bind it with `comptime` at file scope (above `main`) to that 4-lane float32 SIMD type so it is in scope when `main` constructs it. (Mojo’s older `alias` keyword still works but is deprecated in favour of `comptime`.)',
},
{
id: 'MQ-214',
concept: "Math operations on SIMD values are applied elementwise, on each individual element in the vector",
title: 'Combine per-axis counts from two IMUs',
topic: 'SIMD & DType',
priority: 'High',
docUrl: `${DOCS}/types/#simd-and-dtype`,
file: 'src/imu_counts.mojo',
description:
'Two IMUs each report how many samples they captured across four axes, ' +
'stored as `SIMD` integer vectors. `combine_counts` should return the ' +
'per-axis totals, but right now it returns only the first IMU. SIMD ' +
'addition is lane-wise, so adding the two vectors gives `[11, 22, 33, 44]`. ' +
'Return the sum of the two IMUs.\n\n' +
'Example: `var result = someVector + anotherVector`',
starter: `def combine_counts(
a: SIMD[DType.int32, 4], b: SIMD[DType.int32, 4]
) -> SIMD[DType.int32, 4]:
return a
def main():
var imu_a = SIMD[DType.int32, 4](1, 2, 3, 4)
var imu_b = SIMD[DType.int32, 4](10, 20, 30, 40)
print("Combined counts:", combine_counts(imu_a, imu_b))
`,
validation: { kind: 'run', expectedStdout: 'Combined counts: [11, 22, 33, 44]' },
hint: 'The helper returns only the first IMU as written. Combine both vectors with the addition operator — on SIMD values it adds lane by lane — and return that instead.',
},
{
id: 'MQ-215',
concept: "`String` supports a variety of operators and common methods, such as `upper()`",
title: 'Emit device tags in uppercase',
topic: 'Strings',
priority: 'High',
docUrl: 'https://mojolang.org/docs/std/builtin/string_literal/StringLiteral/#upper',
file: 'src/device_tag.mojo',
description:
'The fleet registry only accepts uppercase device tags, but `device_tag` ' +
'returns the joined string as-is, so it emits `mq-amr`. A `String` is ' +
'Mojo’s text type, and it offers operators that combine strings (`"str" + "str"`) ' +
'and transformational methods (`"str".someTransformMethod()`) that return a ' +
'transformed copy rather than changing the original. Call the String ' +
'method that returns an upper-cased copy on the finished tag.\n\n' +
'Example: `someString.someTransformMethod()` applied to the whole joined result.',
starter: `def device_tag(family: String, model: String) -> String:
return family + "-" + model
def main():
print(device_tag("mq", "amr"))
`,
validation: { kind: 'run', expectedStdout: 'MQ-AMR' },
hint: 'The pieces are joined correctly, but the registry only accepts a single case. String has a method that returns an upper-cased copy — apply it to the whole joined tag, watching the parentheses so the entire string is transformed.',
},
{
id: 'MQ-219',
concept: "Index a `List` with `list[i]` to read an element; assign to `list[i]` to replace it in place",
title: 'Correct the first waypoint in the path',
topic: 'Collections',
priority: 'High',
docUrl: `${DOCS}/types/#list`,
file: 'src/path.mojo',
description:
'The path planner received a corrected coordinate for the first waypoint, ' +
'but the fix code calls `path.append(corrected)` instead of replacing the ' +
'existing element. `append` adds a new slot at the end, so the path grows ' +
'to four waypoints and `path[0]` still holds the stale value.\n\n' +
'Read and write individual elements with the subscript operator: ' +
'`path[i]` reads the element at index `i`, and `path[i] = value` replaces ' +
'it in place. Fix the code so `path[0]` holds `15` and the list stays ' +
'three elements long.\n\n' +
'Example: `myList[0] = newValue`',
starter: `def main():
var path: List[Int] = [10, 20, 30]
var corrected = 15
path.append(corrected) # TODO: replace path[0] instead of appending
print("first waypoint:", path[0])
print("waypoints:", len(path))
`,
validation: { kind: 'run', expectedStdout: 'first waypoint: 15\nwaypoints: 3' },
hint: 'Remove the `append` call and write directly to the slot: `path[0] = corrected`.',
},
{
id: 'MQ-220',
concept: "A `Tuple` is an ordered collection; unpack it or index it to get individual values",
title: 'Unpack the telemetry stats in the right order',
topic: 'Tuples',
priority: 'High',
docUrl: `${DOCS}/types/#tuples`,
file: 'src/telemetry.mojo',
description:
'The telemetry panel reads a `(scans, points)` tuple, but it unpacks the two ' +
'slots in the wrong order, so the labels are swapped. A tuple keeps elements ' +
'in the order they were packed — line up each index with its position.\n\n' +
'Example: read `someTuple[0]` and `someTuple[1]` to match how the pair was built.',
starter: `def scan_stats() -> Tuple[Int, Int]:
var num_scans = 4
var total_points = 512
return (num_scans, total_points)
def main():
var stats = scan_stats()
var scans = stats[1]
var points = stats[0]
print("scans:", scans)
print("points:", points)
`,
validation: { kind: 'run', expectedStdout: 'scans: 4\npoints: 512' },
hint: 'A tuple keeps its elements in the order they were packed. The pair is built as (scans, then points), but the two reads pull from the opposite slots. Match each index to the position it was placed in.',
},
{
id: 'MQ-221',
concept: "A given `List` can only hold one type of value, specified at compile time as a parameter",
title: 'Type the waypoint queue',
topic: 'Collections',
priority: 'High',
docUrl: `${DOCS}/types/#list`,
file: 'src/waypoints.mojo',
description:
'A `List[T]` is a growable, ordered sequence whose elements all share one ' +
'type `T`, fixed at compile time. The waypoint queue is created as an ' +
'untyped `List()`, so Mojo cannot infer its element type and the build ' +
"fails. We're storing waypoint ids as `Int`s — annotate the element " +
'type.\n\n' +
'Example: `var someList = List[SomeType]()`',
starter: `def main():
var waypoints = List()
waypoints.append(128)
waypoints.append(256)
print("Queued waypoints:", len(waypoints))
`,
validation: { kind: 'run', expectedStdout: 'Queued waypoints: 2' },
hint: '`List` is generic, so it must know what it holds. Specify the element type in square brackets when you construct it.',
},
{
id: 'MQ-222',
concept: "`Dict` holds key-value pairs; specify the key type and value type as parameters",
title: 'Compile the joint-angle lookup',
topic: 'Collections',
priority: 'High',
docUrl: `${DOCS}/types/#dict`,
file: 'src/joint_map.mojo',
description:
'The controller tracks each joint’s last commanded angle in a `Dict`. A ' +
'`Dict[K, V]` maps keys of type `K` to values of type `V` — here ' +
'`Dict[String, Int]` maps a joint id to an angle. You write an entry with ' +
'`d[key] = value`, read it back with `d[key]`, and count the entries with ' +
'`len(d)`.\n\n' +
'This `main` is incomplete on two counts. First, only `joint_3` is ' +
'recorded — add `joint_8` at an angle of `256` with `d[key] = value` so the ' +
'map holds two joints. Second, reading `d[key]` raises if the key is ' +
'absent, so a key lookup is a raising call; `main` performs one ' +
'(`joint_angles["joint_3"]`) but does not declare that it can raise, so it ' +
'will not compile. Record the second joint and mark `main` as raising.\n\n' +
'Example: `def someFunction() raises:`',
starter: `from std.collections import Dict
def main():
var joint_angles = Dict[String, Int]()
joint_angles["joint_3"] = 128
# TODO: also record joint_8 at an angle of 256
print("joint angle:", joint_angles["joint_3"])
print("joints:", len(joint_angles))
`,
validation: { kind: 'run', expectedStdout: 'joint angle: 128\njoints: 2' },
hint: 'Two fixes. Add the missing entry with `joint_angles["joint_8"] = 256`. And because looking a key up in a `Dict` can fail when the key is absent, that read is a raising call — a function that calls something raising must advertise it, so add `raises` to the header of `main`.',
},
{
id: 'MQ-223',
concept: "`Set` represents a collection of unique values",
title: 'Deduplicate sensor ids with a Set',
topic: 'Collections',
priority: 'Medium',
docUrl: `${DOCS}/types/#set`,
file: 'src/unique_ids.mojo',
description:
'A `Set` is created as an untyped `Set()`, so Mojo cannot infer its element ' +
'type and the build fails. We are tracking unique sensor ids as `Int`s — ' +
'annotate the element type. A set keeps only distinct values, so adding 1 ' +
'twice still leaves two unique ids.\n\n' +
'Example: `var s = Set[SomeType]()`',
starter: `from std.collections import Set
def main():
var seen = Set()
seen.add(1)
seen.add(1)
seen.add(2)
print("unique:", len(seen))
`,
validation: { kind: 'run', expectedStdout: 'unique: 2' },
hint: 'Specify the element type when constructing: `Set[Int]()`.',
},
{
id: 'MQ-224',
concept: 'An `Optional` represents a value that may or may not be present',
title: 'Type a calibration-cache miss',
topic: 'Options',
priority: 'High',
docUrl: `${DOCS}/types/#optional`,
file: 'src/calib_cache.mojo',
description:
'`cache_lookup` returns a value on a hit and `None` on a miss, but its ' +
'return type is `Int` — which cannot hold `None`. Fix it so the function ' +
'can return either. You will need to import `Optional` from ' +
'`std.collections` and update the return type.\n\n' +
'Example:\n```\nfrom std.collections import Optional\n\ndef find(x: Int) -> Optional[Int]:\n if x > 0:\n return x\n return None\n```',
starter: `def cache_lookup(sensor_id: Int) -> Int:
if sensor_id == 7:
return 512
return None
def main() raises:
var hit = cache_lookup(7)
var miss = cache_lookup(3)
if hit:
print('hit:', hit.value())
else:
print('hit:', hit)
if miss:
print('miss:', miss.value())
else:
print('miss:', miss)
`,
validation: { kind: 'run', expectedStdout: 'hit: 512\nmiss: None' },
hint: 'The return type `Int` cannot represent “no value”. Import the right type from `std.collections` and use it as a wrapper around `Int` in the return annotation — that tells Mojo the function may return nothing.',
},
{
id: 'MQ-301',
concept: "Exponentiation uses two stars (`**`), not a caret",
title: 'Square the value with exponentiation',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#arithmetic-operators`,
dayDocUrls: [
{ label: 'Operators', url: `${DOCS}/operators/` },
{ label: 'Control flow', url: `${DOCS}/control-flow/` },
],
file: 'src/exponent.mojo',
description:
'`square_area` should return its `side` raised to the power 2, but it ' +
'multiplies the side by 2 instead of squaring it, so `square_area(4)` ' +
'returns 8 instead of 16. Exponentiation uses the `**` operator ' +
'(`base ** exp`), not a caret. Use the exponentiation operator.\n\n' +
'Example: `var sq = base ** 2`',
starter: `def square_area(side: Int) -> Int:
return side * 2
def main():
print("area:", square_area(4))
`,
validation: { kind: 'run', expectedStdout: 'area: 16' },
hint: 'Multiplying by 2 only doubles. Reach for the exponentiation operator (`**`) to raise the side to the power 2.',
},
{
id: 'MQ-302',
concept: "Use `//` for floor division; the modulo operator `%` returns the remainder",
title: 'Split readings into full bins',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#arithmetic-operators`,
file: 'src/divmod.mojo',
description:
'`split_into_bins` should report how many full bins of 5 fit into 17 ' +
'readings (`17 // 5` = 3) and how many are left over (`17 % 5` = 2). Floor ' +
'division `//` keeps only the whole number of times one value divides ' +
'another, while the modulo operator `%` returns the remainder. But the ' +
'two operators are swapped, so it returns `(2, 3)` and prints ' +
'`bins: 2 left: 3`. Put floor division `//` on the bin count and remainder ' +
'`%` on the leftovers.\n\n' +
'Example: `var count = total // size`, `var rest = total % size`',
starter: `def split_into_bins(total: Int, per_bin: Int) -> Tuple[Int, Int]:
return total % per_bin, total // per_bin
def main():
var result = split_into_bins(17, 5)
print("bins:", result[0], "left:", result[1])
`,
validation: { kind: 'run', expectedStdout: 'bins: 3 left: 2' },
hint: '`//` gives the whole number of bins; `%` gives the remainder. They are swapped — exchange them.',
},
{
id: 'MQ-303',
concept: "Mojo provides six comparison operators: `==`, `!=`, `<`, `<=`, `>`, and `>=`, each returning a `Bool`",
title: 'Flag a low battery at the threshold',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#comparison-operators`,
file: 'src/compare.mojo',
description:
'Mojo’s comparison operators — `==`, `!=`, `<`, `<=`, `>`, and `>=` — test ' +
'two values and return a `Bool`. `battery_low` should count a battery at ' +
'exactly 20% as low, but it uses a strict `<`, so 20 is not flagged. Use ' +
'the operator that also includes the threshold itself.\n\n' +
'Example: `value <= limit`',
starter: `def battery_low(level: Int) -> Bool:
return level < 20
def main():
print("low:", battery_low(20))
`,
validation: { kind: 'run', expectedStdout: 'low: True' },
hint: 'A strict `<` excludes the boundary. Use `<=` so 20 counts as low.',
},
{
id: 'MQ-304',
concept: "You can chain comparisons; `a < b < c` is equivalent to `(a < b) and (b < c)`",
title: 'Bound-check with a chained comparison',
topic: 'Operators',
priority: 'Low',
docUrl: `${DOCS}/operators/#comparison-operators`,
file: 'src/chained.mojo',
description:
'`in_range` should reject a temperature outside the safe band of 0–85, but ' +
'it only tests the lower bound, so 90°C reports in-range. A chained ' +
'comparison like `a < b < c` tests several relations at once, equivalent to ' +
'`(a < b) and (b < c)`. Use a chained comparison to test both bounds at ' +
'once.\n\n' +
'Example: `lo <= x <= hi`',
starter: `def in_range(temp: Int) -> Bool:
return 0 <= temp
def main():
print("in range:", in_range(90))
`,
validation: { kind: 'run', expectedStdout: 'in range: False' },
hint: 'Extend the single comparison into a chained one that also tests the upper bound (85) in the same expression.',
},
{
id: 'MQ-305',
concept: "Bitwise OR (`|`) keeps bits that are set in either operand",
title: 'Combine status flags with bitwise OR',
topic: 'Operators',
priority: 'Low',
docUrl: `${DOCS}/operators/#bitwise-operators`,
file: 'src/flags.mojo',
description:
'`status_word` should carry both the READY and ARMED bits, but it ANDs the ' +
'two flag bits together (clearing everything) instead of ORing them, so the ' +
'ARMED test reads false. Bitwise OR (`|`) keeps every bit that is set in ' +
'either operand. Combine the flags with bitwise OR.\n\n' +
'Example: `var flags = A | B`',
starter: `def status_word(ready: Int, armed: Int) -> Int:
return ready & armed
def main():
var READY = 1
var ARMED = 2
var flags = status_word(READY, ARMED)
print("armed:", (flags & ARMED) != 0)
`,
validation: { kind: 'run', expectedStdout: 'armed: True' },
hint: 'Combining flags means setting both bits — that’s bitwise OR (`|`), not AND. The `&` in the test below is correct; it checks whether a bit is set.',
},
{
id: 'MQ-306',
concept: "With `and`, both operands must be truthy; if the left side is falsy, the right side isn't evaluated",
title: 'Require both preconditions',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#boolean-operators`,
file: 'src/preconditions.mojo',
description:
'The robot may only drive when it has a position fix AND is calibrated, but ' +
'`can_drive` uses `or`, so it would go with either one alone. With boolean ' +
'`and`, both operands must be truthy; it also short-circuits, skipping the ' +
'right side when the left is false. Use boolean `and` so both must ' +
'hold.\n\n' +
'Example: `var ready = cond_a and cond_b`',
starter: `def can_drive(has_fix: Bool, calibrated: Bool) -> Bool:
return has_fix or calibrated
def main():
print("go:", can_drive(True, False))
`,
validation: { kind: 'run', expectedStdout: 'go: False' },
hint: 'Replace `or` with `and` so both preconditions are required before driving.',
},
{
id: 'MQ-308',
concept: "The `in` operator checks whether a collection contains a value",
title: 'Check membership in the allow-list',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#membership-operators`,
file: 'src/membership.mojo',
description:
'`is_allowed` should report whether a sensor id is in the allow-list, but it ' +
'uses `not in`, so it returns the opposite of what we want. The `in` ' +
'operator checks whether a collection contains a value, and `not in` is its ' +
'negation. Use the membership operator that tests for presence.\n\n' +
'Example: `value in container`',
starter: `def is_allowed(sensor_id: Int, allowed: List[Int]) -> Bool:
return sensor_id not in allowed
def main():
var allowed: List[Int] = [2, 4, 6]
print("ok:", is_allowed(4, allowed))
`,
validation: { kind: 'run', expectedStdout: 'ok: True' },
hint: 'You want to test for presence, not absence — drop the `not` so it uses the plain membership operator.',
},
{
id: 'MQ-309',
concept: "A conditional expression has the form `value_if_true if condition else value_if_false`",
title: 'Pick a label with a conditional expression',
topic: 'Operators',
priority: 'Medium',
docUrl: `${DOCS}/operators/#conditional-expressions`,
file: 'src/ternary.mojo',
description:
'`speed_label` chooses its label with C-style ternary syntax ' +
'(`cond ? a : b`), which Mojo does not accept. A conditional expression in ' +
'Mojo has the form `value_if_true if condition else value_if_false`. ' +
'Rewrite it using Mojo’s conditional expression.\n\n' +
'Example: `value_if_true if condition else value_if_false`',
starter: `def speed_label(speed: Int) -> String:
return speed > 10 ? "fast" : "slow"
def main():
print("mode:", speed_label(12))
`,
validation: { kind: 'run', expectedStdout: 'mode: fast' },
hint: 'Mojo has no `? :` operator. Rewrite it in the `value if condition else other` form.',
},
{
id: 'MQ-310',
concept: "Compound assignment forms like `*=` update the left-hand value instead of creating a new one",
title: 'Scale a value in place',
topic: 'Operators',
priority: 'Low',
docUrl: `${DOCS}/operators/#assignment-operators`,
file: 'src/assign_op.mojo',
description:
'The gain should be tripled in place, but the code overwrites it with `3` ' +