问题
I tried to create a sqrt+
function, which will get a list of numbers and return a list of numbers. Can anyone tell me what's wrong with the function?
#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
回答1:
In the else
case, you should use:
(let ([s (sqrt (first ns))])
(cons s
(cons (* s -1)
(sqrt+ (rest ns)))))`
回答2:
The else cause needs to be different, and when you have an empty list, the return type should also be an empty list, and not a number. So, the return of the first clause of your cond should be "null" or "nil". Try using the below instead (the syntax might have to be tweaked a bit):
(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))))]))
来源:https://stackoverflow.com/questions/37645573/create-sqrt-function-in-racket