CDuce - gregorymorrison/euler1 GitHub Wiki

CDuce is an interesting beast. Introduced in 2007, it can probably best be described as a variant of XSLT written in OCaml. It's designed as a transformation language for XML, but it includes just enough functional programming to make it Turing-complete. If you try to approach this from an imperative/OOP mindset, you're gonna have a bad time. I had a bad time with this language; it took me maybe a week to write this version of Euler1. You can see that it mostly looks like OCaml; there's no mutable state in this language:

(* Euler1 in CDuce *)

let euler ((Int,Int) -> Int)
 | (0 | 1, x) -> x
 | (n, x) -> 
    if (n mod 3 = 0) || (n mod 5 = 0) then  
        euler (n - 1, x + n)
    else
        euler (n - 1, x);;

let euler1 (size : Int) : Int = euler (size, 0);;

print (string_of (euler1(999)) @ "\n");;

I found this language to be very frustrating. Error messages are almost useless - the line numbers and character positions in them are all wrong. Documentation and examples are very sparse. Whitespace is significant though neither the documentation nor the compiler errors let you know the whitespace rules. It actually took me a couple of months to figure out how to write FizzBuzz in this language:

(* FizzBuzz in CDuce *)

let format (n : Int) : Latin1 =
    if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz"
    else if (n mod 5 = 0) then "Buzz"
    else if (n mod 3 = 0) then "Fizz"
    else string_of (n);;

let fizz (n : Int, size : Int) : _ = 
    print (format (n) @ "\n");
    if (n = size) then
        n = 0 (* do nothing *)
    else
        fizz(n + 1, size);;

let fizbuzz (size : Int) : _ = fizz (1, size);;

let _ = fizbuzz(100);;

If you are masochistic enough to want to tackle it yourself, simply apt install cduce, then execute your code by passing it in to the runtime as an argument:

$ cduce euler1.cd
233168
$