Mentions légales du service

Skip to content
Snippets Groups Projects

FizzBuzz in CUE

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by PERDEREAU Eloi

    This FizzBuzz implementations in CUE, a simple example of a standard program written in a logic structural paradigm.

    In a few lines, we can elaborate on many CUE core concepts, e.g. emit values, hidden fields, if-then-else, comprehensions, embedding, lists, ...

    We can execute our program in the CLI with

    cue def fizzbuzz.cue | cat - <(echo '#max: 21') | cue export - --out=text

    The cat - <(echo '#max: 21') part adds to fizzbuzz.cue a refinement of the #max value, thus taking precedence on the default in the file. It is equivalent to having set some input parameters values to our CUE script.

    Edited
    fizzbuzz.cue 1.48 KiB
    // cue def fizzbuzz.cue | cat - <(echo '#max: 21') | cue export - --out=text
    import (
      "list"
      "strings"
    )
    
    #max: *100 | uint
    
    // string
    _script.out
    
    _script: {
    
      // According to _n's divisibility, a string "FizzBuzz", "Fizz", "Buzz" or "_n"
      method: fizzbuzz4
    
      fbs: [ for i in list.Range(0,#max,1) { method, _n: i } ]
      ns_fbs: [ for idx, fb in fbs { "\(idx)\t: \(fb)" } ]
      out: strings.Join(ns_fbs, "\n")
    
      fizzbuzz1: string & {
        _n: int // "parameter" field
        [ // if-then-else emit value
          if _n mod 15 == 0 { "FizzBuzz" },
          if _n mod  3 == 0 { "Fizz" },
          if _n mod  5 == 0 { "Buzz" },
          "\(_n)"
        ][0]
      }
    
      fizzbuzz2: string & {
        _n: int, "\(_n)" | *({
          {
            test: (_n mod 3 == 0 && _n mod 5 != 0) & true
            res: "Fizz"
          } | {
            test: (_n mod 3 != 0 && _n mod 5 == 0) & true
            res: "Buzz"
          } | {
            test: (_n mod 3 + _n mod 5) & 0
            res: "FizzBuzz"
          }
        }.res)
      }
    
      fizzbuzz3: string & {
        _n: int, "\(_n)" | *({
          fizz: _n mod 3
          buzz: _n mod 5
        } & (*{
          fizz: 0
          buzz: 0
          res: "FizzBuzz"
        } | {
          fizz: 0
          res: "Fizz"
        } | {
          buzz: 0
          res: "Buzz"
        })).res
      }
    
      fizzbuzz4: string & {
        _n: int
        "\(_n)" | *(_NeStr & strings.Join([_fizz, _buzz], ""))
        _fizz: "" | *(_NeStr & { if _n mod 3 == 0 { "Fizz" } })
        _buzz: "" | *(_NeStr & { if _n mod 5 == 0 { "Buzz" } })
        _NeStr: self={ string, _ne: len(self) & >0 }        // NonEmpty Strings
      }
    
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment