【问题标题】:Writing a scheme function编写方案函数
【发布时间】:2014-04-21 19:40:49
【问题描述】:

如何编写一个函数,该函数将评分函数(我已经编写过)和字符串对列表作为输入(我对如何编写感到困惑),并返回修改后的列表字符串对,其中返回的列表应包含输入中的所有最佳字符串对,根据输入函数评分。

示例输入:

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

示例输出:

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

该函数采用如上所示的字符串对列表。它还接受一个函数。它使用这个函数作为评估字符串对列表的一种手段。然后,它返回一个字符串对列表,其中包含所有具有最高匹配分数的字符串对,这些字符串对基于它被赋予用于评估它们的函数。换句话说, (("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow")) 的分数都是 -3,但是 ("h_e_llo" "bl_o__w")) -12 分,因此从列表中删除。

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

【问题讨论】:

标签: functional-programming scheme gambit


【解决方案1】:

我会将操作分为两个步骤。

  1. 计算最高分。这是一个可以做到这一点的函数。

    (define (get-maximum-score lst scoring-func)
     (apply max (map (lambda (x) (scoring-func (car x) (cadr x))) lst)))
    
  2. 通过选择与最高分匹配的项目来过滤列表并删除其余的。

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

现在得到结果。

(print
 (get-maximum-score-items
  '(("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") ("hello" "blow") ("h_e_llo" "bl_o__w"))
     alignment-score))

【讨论】:

  • 我试过了,说传递给过程的参数数量错误?我想添加其他东西吗?
  • @Definer 我的回答中有一些拼写错误。再次尝试这些功能。
  • 我仍然得到一个错误类型,先生,它说 Map 中的错误 -- 传递给过程的参数数量错误 (score-function '("hello" "b_low"))
  • @Definer 你能发布你的评分函数吗?
  • (define (scoring-function char1 char2) (cond ((char=?char1 char2) 2) ((or (char=? char1 #_ ) (char=? #_ char2)) - 2) (else -1))) and also (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 (scoring-function (string-ref s1 index) (string-ref s2 index)))(+ index 1 )))))
猜你喜欢
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多