create sqrt function in racket

被刻印的时光 ゝ 提交于 2019-12-13 22:47:43

问题


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

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