interlacep.scm

#!/usr/bin/env racket
#lang racket

2. Naprogramujte predikát interlaced?, který vrací #t, pokud je jeho argument seznam liché délky (nebo je prázdný) a prvky na sudých pozicích jsou si rovny. Predikát vlastně zjištuje, jestli seznam mohl vzniknout použitím procedury interlace z předchozího příkladu.

(define (interlace l x)
  (if (or (null? l) (null? (cdr l)))
    l;'() nebo (?): hotovo
    (foldr
      (lambda (e t) (cons e (cons x t)))
      (cons (car l) '());(car l) nestaci, lze i `(,(car l))
      (cdr l))))
(interlace '()       'x)
(interlace '(1)      'x)
(interlace '(1 2)    'x)
(interlace '(1 2 3)  'x)

predikat pro následujíci tvar: '(x ? x ? … x ?)

(define (x? x l) 
  (cond ((null? l) #t)
        ((null? (cdr l)) #f) ;delka 1
        ((equal? x (car l)) (x? x (cddr l)));ukousneme 2 a ocasni rekurze
        (else #f)))
 
(x? 'x '()) ;#t
(x? 'x '(x)) ;#f
(x? 'x '(x 1)) ;#t
(x? 'x '(x 1 x 2 x)) ;#f
(x? 'x '(x 1 x 2 x 3)) ;#t
(x? 'x '(x 1 x 2 y 3 y 4)) ;#f
'(#t #f #t #f #t #f (testujeme x?))
(map (lambda (l) (x? 'x l)) '(() (x) (x 1) (x 1 x 2 x) (x 1 x 2 x 3) (x 1 x 2 y 3 y 4)))

interlaced? je varianta na x?

(define (interlaced? l)
  (or (null? l)
      (null? (cdr l)) ;'() a (?) jsou #t
      (x? (cadr l) (cdr l)) ;x? inline jako named let? letrec?
      ))

Příklady použití:

(interlaced? '())          ;⇒ #t
(interlaced? (list 1))     ;⇒ #t
(interlaced? (interlace (list 1 2 3) 'x)) ;⇒ #t
(interlaced? '(1 x 2 x))   ;⇒ #f
(interlaced? '(x 1 x 2 x)) ;⇒ #f
(interlaced? '(x x x))     ;⇒ #t
 
'(qq:)
(define test1 `(() ,(list 1) ,(interlace (list 1 2 3) 'x) (1 x 2 x) (x 1 x 2 x) (x x x)))
test1
'(#t #t #t #f #f #t (testujeme interlaced?))
(map interlaced? test1)
 
 
 ; vim: syntax=racket
YPP1/ypp1du/interlacep.scm.txt · Last modified: 2014/03/14 22:22 (external edit)
CC Attribution-Noncommercial-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0