• Re: Can you help me get rid of the setf?

    From B. Pym@21:1/5 to All on Tue Aug 27 07:19:53 2024
    XPost: comp.lang.scheme

    Frank Buss <[email protected]> writes:
    Looks like you are searching for a functional way of doing this. In Haskell you could write it like this (I'm a Haskell newbie, I'm sure this can be written better, but at least it works)

    f (x,y) = 9*x + 4*y - x*x - y*y
    best = foldr1 max values
    where values = [(f(x,y), (x,y)) | x<-[0..9], y<-[0..9]]
    max t1 t2 = if (fst t1) >= (fst t2) then t1 else t2

    let f x y = 9*x+4*y-x*x-y*y in
    foldl1' max [(f x y,(x,y)) | x <- [0..9], y<-[0..9]]

    is a little simpler. Uses the max built-in and foldl1' which operates
    left to right and is strict.

    Gauche Scheme

    (use gauche.collection)
    (use util.combinations)

    (let1 f (^(x y) (+ (* 9 x) (* 4 y) (* x (- x)) (* y (- y))))
    (find-max
    (map (^x (list (apply f x) x))
    (cartesian-product (list (iota 10) (iota 10))))
    :key car))

    (24 (5 2))

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From B. Pym@21:1/5 to andrew.baine on Sat Aug 2 07:04:18 2025
    XPost: comp.lang.scheme

    andrew.baine wrote:

    I'm looping over two variables to maximize a function, returning x and
    y that maximize f. Any way to do it without the setf in the body?

    ; Here's a function you can paste to the REPL.

    (defun f (x y)
    (- (+ (* 9 x) (* 4 y))
    (* x x)
    (* y y))

    A parenthesis is missing.


    ; And here's what I'm trying to do:

    (let ((best-x -1)
    (best-y -1)
    (max nil))
    (loop :for x :below 10 :do
    (loop :for y :below 10 :do
    (let ((n (f x
    y)))
    (if (or (null max) (> n
    max))
    (setf best-x
    x
    best-y
    y
    max n)))))
    (values best-x best-y))


    Gauche Scheme

    (use util.combinations) ;; cartesian-product
    (use gauche.collection) ;; find-max

    (define (f x y)
    (- (+ (* 9 x) (* 4 y))
    (* x x)
    (* y y)))

    (find-max
    (cartesian-product (list (iota 10) (iota 10)))
    :key (cut apply f <>))

    ===>
    (5 2)

    Another solution: (4 2)

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)