简体   繁体   中英

How to implement the haskell `\\` function?

In haskell, [1,2,3,4,5,6,7] \\\\ [4,5,6] will return [1,2,3,7] . Now i want to implement the same function using clisp. Up to now i find set-difference works :

(set-difference '(1 2 3 4 5 6 7) '(4 5 6))

Are there any other solution ?

Here are relevant bits of haskell library source. Maybe you can translate these definitions directly. I don't think it uses anything specific to Haskell.

(the source is from http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-List.html )

delete                  :: (Eq a) => a -> [a] -> [a]
delete                  =  deleteBy (==)

-- | The 'deleteBy' function behaves like 'delete', but takes a
-- user-supplied equality predicate.
deleteBy                :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy _  _ []        = []
deleteBy eq x (y:ys)    = if x `eq` y then ys else y : deleteBy eq x ys

(\\)                    :: (Eq a) => [a] -> [a] -> [a]
(\\)                    =  foldl (flip delete)

I don't know Common Lisp that well, so here's a Scheme implementation of the code pasted by Ben:

(define (difference big small)
  (fold delete big small))

(define (delete x lst)
  (delete-by equal? x lst))

(define (delete-by equal? x lst)
  (if (null? lst) '()
      (receive (y ys) (car+cdr lst)
        (if (equal? x y) ys
            (cons y (delete-by equal? x ys))))))

where fold and car+cdr come from SRFI 1 , and receive comes from SRFI 8 .


If we will allow ourselves the use of SRFI 26 's cut form, then we have a solution that looks even closer to the Haskell version (since the latter uses currying in at least two places):

(define difference (cut fold delete <...>))
(define delete (cut delete-by equal? <...>))

; Unchanged from the above version
(define (delete-by equal? x lst)
  (if (null? lst) '()
      (receive (y ys) (car+cdr lst)
        (if (equal? x y) ys
            (cons y (delete-by equal? x ys))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM