我尝试创建一个sqrt+
函数,它将获取一个数字列表并返回一个数字列表。谁能告诉我这个功能有什么问题?
#lang pl 03
(: sqrt+ : (Listof Number) -> (Listof Number))
;; a version of `sqrt' that takes a list of numbers, and return a list
;; with twice the elements, holding the two roots of each of the inputs;
;; throws an error if any input is negative.
(define (sqrt+ ns)
(cond [(null? ns) 0]
[(< (first ns) 0) (error 'ns "`sqrt' requires a nonnegative input ~s")]
[else ((sqrt ns) (* (sqrt ns) -1))]))
Type Checker: type mismatch
expected: (Listof Number)
given: Zero
in: 0
Type Checker: type mismatch
expected: Nonnegative-Real
given: (Pairof Nonnegative-Real (Listof Number))
in: ns
Type Checker: type mismatch
expected: Nonnegative-Real
given: (Pairof Nonnegative-Real (Listof Number))
in: ns
Type Checker: Summary: 3 errors encountered
in:
0
ns
ns
答案 0 :(得分:1)
在else
案例中,您应该使用:
(let ([s (sqrt (first ns))])
(cons s
(cons (* s -1)
(sqrt+ (rest ns)))))`
答案 1 :(得分:0)
其他原因需要不同,当你有一个空列表时,返回类型也应该是一个空列表,而不是一个数字。所以,你的cond的第一个条款的返回应该是&#34; null&#34;或者&#34; nil&#34;。 请尝试使用以下代码(语法可能需要稍微调整一下):
(define (sqrt+ ns)
(cond [(null? ns) ns]
[(< (first ns) 0) (error 'ns "`sqrt' requires a nonnegative input ~s")]
[else (cons (sqrt (first ns))
(cons (* -1 (sqrt (first ns)))
(sqrt+ (rest ns))))]))