/* This may look like a -*- C -*- code, but it's only similiar.
 *
 *    Calc: A Programmable Calculator for GTK+
 *    Copyright (C) 2000  David Hanak (dhanak@inf.bme.hu)
 *
 *    This file can be distributed under GNU GPL.  See file COPYING.
 *
 *    $Id: integration,v 2.0 2000/02/16 16:47:40 david Exp $
 * 
 * This is an example for Calc.
 */

/* This file demonstrates how to program `calc' through a simple analytical
 * integration problem.
 */

// This function reads a value and evaluates "pre" "answer" "post" string.
// If the evaluation fails, prompts again.
fun readexpr(mesg, pre, post) =
{
  var v;
  do v = read(strcat(mesg, ": "))
  while (iserr(v = eval(strcat(pre, v, post))));
  v
};

fun integrate() =
{
  var(res, start, end, step);

  // Read function and parameters
  do readexpr("Expression in terms of x", "fun user(x) = {", "}")
  while (iserr(user(1)));
  start = readexpr("Lower limit", "", "");
  end = readexpr("Upper limit", "", "");
  step = readexpr("Stepping", "", "");
  
  res = 0; // This variable will store the result
  for (x = start, x < end, x += step)
    res += (user(x) + user(x+step)) / 2 * step;
  
  msg(strcat("The result is ", res));
  
  res
};

integrate()
