Writing a scheme function

2019-09-01 01:35发布

How do I write a function that takes both a scoring function (which I've written already) and a list of pairs of strings as input (which I'm confused on how to write), and returns a modified list of pairs of strings, where the returned list should contain all the optimal string pairs from the input, scored according to the input function.

Example input:

'( ("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") ("hello" "blow") ("h_e_llo" "bl_o__w") )

Example output:

( ("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") )

the function takes a list of pairs of strings as shown above. It also takes in a function. It uses this function that it takes in as a means to evaluate the list of pairs of strings. It then returns a list of pairs of strings containing all of the pairs of strings that had the highest match-score based on the function it was given to evaluate them with. In other words, (("hello" "b_low") ("hello_" "b_l_ow") ("hello" “_blow")) all had the same score of -3, but ("h_e_llo" “bl_o__w”)) has a score of -12, thus it is dropped from the list.

The functions to compute alignemt:

(define (char-scorer char1 char2)
  (cond 
    ((char=? char1 char2) 2)
    ((or (char=? char1 #\_ ) (char=? #\_ char2)) -2)
    (else -1)))

(define (alignment-score s1 s2)
  (define min-length (min (string-length s1) (string-length s2)))
  (let loop ((score 0) (index 0))
    (if (= index min-length)
      score
      (loop (+ score (char-scorer (string-ref s1 index) (string-ref s2 index)))(+ index 1))))) 

1条回答
仙女界的扛把子
2楼-- · 2019-09-01 02:19

I would divide the operation into two steps.

  1. Compute the maximum score. Here's a function that can do that.

    (define (get-maximum-score lst scoring-func)
     (apply max (map (lambda (x) (scoring-func (car x) (cadr x))) lst)))
    
  2. Filter the list by selecting the items that match the maximum score and drop the rest.

    (define (get-maximum-score-items lst scoring-func)
    
      (define max-score (get-maximum-score lst scoring-func))
    
      (define (helper in out)
        (if (null? in)
          out
          (if (eq? max-score (scoring-func (caar in) (cadar in)))
            (helper (cdr in) (append out (list (car in))))
            (helper (cdr in) out))))
    
      (helper lst '())
      )
    

Now get the result.

(print
 (get-maximum-score-items
  '(("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") ("hello" "blow") ("h_e_llo" "bl_o__w"))
     alignment-score))
查看更多
登录 后发表回答