Longest decreasing sequence in Lisp

后端 未结 3 867
情深已故
情深已故 2021-01-21 20:44

I\'m working on some problems for my upcoming exam and I need some help with this Lisp function. I\'m working in CLISP. I have to find the longest decreasing sequence comprised

3条回答
  •  醉话见心
    2021-01-21 20:48

    The algorithm as in Daniel's answer translated into Haskell, with some tweaks:

    longest_sub xs = g2 xs [] 0 
      where
        g2 [] a _ = a
        g2 (x:t) a i  
             | even x    = g2 t a i 
             | otherwise = g4 t [x] 1
          where
            g4 [] b j = if j>i then reverse b else reverse a
            g4 xs@(x:t) b j            
                 | even x || x >= head b
                             = if j>i then g2 xs b j 
                                      else g2 xs a i 
                 | otherwise = g4 t (x:b) (j+1)
    

    In Common Lisp:

    (defun longest (xs)
      (prog  ((a nil) (i 0) b j x)                  ; var decls
          G2  (if (null xs) (return (reverse a)))   ; code
              (setf x (car xs) xs (cdr xs))
              (if (evenp x)
                  (go G2))
          G3  (setf b (list x) j 1)
          G4  (if (null xs)
                  (if (> j i)
                      (return (reverse b))
                      (return (reverse a))))
              (setf x (car xs) xs (cdr xs))
              (when (evenp x)
                  (if (> j i) (setf a b i j))
                  (go G2))
              (when (>= x (car b))
                  (if (> j i) (setf a b i j))
                  (go G3))
              (setf b (cons x b) j (+ j 1))
              (go G4)))
    

    Function call is a glorified GOTO after all, isn't it?

    see also: prog doc page.

提交回复
热议问题