; Fieldtest — Floats milestone, axis 2: Int/Float interop.
;
; Compute the arithmetic mean of an Int list and print it as a Float.
; Sum is Int (no overflow risk for the inputs we use); count is Int;
; the divide must happen in Float space so we get a fractional result.
;
; This is the canonical task that exercises int_to_float at both
; converted operands. The literal `2` cannot be shared with Float
; arithmetic, so the natural shape is:
;   (/ (int_to_float sum) (int_to_float count))
;
; Inputs: [1, 2, 3, 4, 6]; sum=16, count=5; mean=3.2.
; Expected stdout: 3.2

(module floats_2_average_int_list

  (data IntList
    (ctor Nil)
    (ctor Cons (con Int) (con IntList)))

  (fn sum_acc
    (doc "Tail-recursive sum with accumulator.")
    (type
      (fn-type
        (params (con IntList) (con Int))
        (ret (con Int))))
    (params xs acc)
    (body
      (match xs
        (case (pat-ctor Nil) acc)
        (case (pat-ctor Cons h t)
          (tail-app sum_acc t (app + acc h))))))

  (fn count_acc
    (doc "Tail-recursive length with accumulator.")
    (type
      (fn-type
        (params (con IntList) (con Int))
        (ret (con Int))))
    (params xs acc)
    (body
      (match xs
        (case (pat-ctor Nil) acc)
        (case (pat-ctor Cons _ t)
          (tail-app count_acc t (app + acc 1))))))

  (fn mean
    (doc "Mean as Float = sum / count, both promoted via int_to_float.")
    (type (fn-type (params (con IntList)) (ret (con Float))))
    (params xs)
    (body
      (app /
        (app int_to_float (app sum_acc xs 0))
        (app int_to_float (app count_acc xs 0)))))

  (fn main
    (type (fn-type (params) (ret (con Unit)) (effects IO)))
    (params)
    (body
      (do io/print_float
        (app mean
          (term-ctor IntList Cons 1
            (term-ctor IntList Cons 2
              (term-ctor IntList Cons 3
                (term-ctor IntList Cons 4
                  (term-ctor IntList Cons 6
                    (term-ctor IntList Nil)))))))))))
