Writing a scheme function

戏子无情 提交于 2019-12-12 04:43:39

问题


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:


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))


来源:https://stackoverflow.com/questions/23204644/writing-a-scheme-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!