MojoでProject Euler 2

https://projecteuler.net/problem=2

Pythonならこんな風に書きたいところです。

from __future__ import annotations
from typing import Iterator
from itertools import takewhile
import sys

def fibs() -> Iterator[int]:
    a, b = 1, 1
    while True:
        yield b
        a, b = b, a + b

def f(N: int) -> int:
    return sum(takewhile(lambda f: f <= N, (f for f in fibs() if f % 2 == 0)))

N = int(sys.argv[1])
print(f(N))

フィボナッチ数列を排出する部分は切り離した方がすっきりするのですが、当然generatorには対応していないので、こう書くでしょうか。

import sys

def f(N: int) -> int:
    s = 0
    a, b = 1, 1
    while b <= N:
        if b % 2 == 0:
            s += b
        a, b = b, a + b
    return s

N = int(sys.argv[1])
print(f(N))

これをMojoにすると、

import sys

fn f(N: Int) -> Int:
    var s = 0
    var a = 1
    var b = 1
    while b <= N:
        if b % 2 == 0:
            s += b
        a, b = b, a + b
    return s

fn main():
    let args = sys.argv()
    try:
        let N = atol(args[1])
        print(f(N))
    except:
        pass

だいたい同じように書けます。