Commit d983d30d authored by Lorenzo Cugini's avatar Lorenzo Cugini

Update TdE/20180905.rkt, TdE/20180905.hs files

parent 51a6ad06
{- A “dual list”, or Dupl, is a pair of independent lists.
1) Define a datatype for Dupl. Can it derive Show and/or Eq? If not, make Dupl an instance of both of them.
2) Make Dupl an instance of Functor, Foldable, and Applicative.
data Dupl a = Dupl [a] [a] deriving (Show, Eq)
duplfoldr :: (a -> b -> b) -> b -> (Dupl a) -> b
-- To make is an instance of Foldable, we just need to implement a fold. Make the foldr called upon l ++ r.
duplfoldr f z (Dupl l r) = foldr f z (l ++ r)
instance Foldable Dupl where
foldr = duplfoldr
instance Functor Dupl where
fmap f (Dupl l r) = Dupl (fmap f l) (fmap f r)
instance Applicative Dupl where
pure x = Dupl [x] []
(Dupl f1 f2) <*> (Dupl x1 x2) = Dupl (f1 <*> x1) (f2 <*> x2)
\ No newline at end of file
#lang racket
; Define in a purely functional way a procedure called revlt, which takes three lists, (x1 ... xL) (y1 ... yM) (z1 .. zN)
; and returns the list of vectors: (#(xO yO zO) ... #(x1 y1 z1)), where O ≥ 1 is the smallest among L, M, and N
;E.g. (revlt '(1 2 3) '(4 5 6 7) '(8 9 10)) is the list '(#(3 6 10) #(2 5 9) #(1 4 8)).
;check how many times an element is inside a vector
(define (numIn vec x)
(let ([count 0] [saved-cont #f] [iteration 0])
(set! iteration (call/cc (lambda(cont) (set! saved-cont cont) (cont 0))))
(when (eq? (vector-ref vec iteration) x)
(set! count (+ count 1)))
(if (eq? iteration (- (vector-length vec) 1))
(saved-cont (+ iteration 1)))))
(define (revlt lst1 lst2 lst3)
; Find O
(let ([minlength (min (length lst1) (length lst2) (length lst3))])
; Create a support vector
(let ([tmp_vec (make-vector minlength -1)] [saved-continuation #f])
(set! saved-continuation cont)
(cont minlength)))
(let ([i (- (vector-length tmp_vec) (numIn tmp_vec -1))]) ; position is 0, 1, 2, 3, ...
(vector-set! tmp_vec i
(quasiquote #(
(unquote (list-ref lst1 i)) (unquote (list-ref lst2 i)) (unquote (list-ref lst3 i))
(when (< i (- minlength 1))
(reverse (vector->list tmp_vec))
;(display (revlt '(1 2 3) '(4 5 6 7) '(8 9 10)))
; The method above works, but it's too long.
(define (revltf l1 l2 l3)
(let loop( [p1 l1] [p2 l2] [p3 l3] [out '()]) ;Prepare a label to construct the list
(if (or (null? p1) (null? p2) (null? p3) ) ;If one list is null, we're over!
(let ( [x1 (car p1)] [x2 (car p2)] [x3 (car p3)] )
(loop (cdr p1) (cdr p2) (cdr p3) (cons (vector x1 x2 x3) out))))))
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment