2016-05-03 38 views
0

我的任务是计算我的列表(列表清单)中的长度为3的列表的数量。 我想我正确地构建了一切,但是当我想将第一个列表发送到递归函数时,它失败了,因为我的列表的类型为Any,而且我找不到使列表成为列表的方式。定义在球拍中接受列表清单的函数

#lang pl 

(: count-3lists : (Listof Any) -> Number) 
(define (count-3lists l) 
    (cond 
    [(null? l) 0] 
    [else (+ (count-3lists-helper (first l)) (count-3lists (rest l)))])) 

(: count-3lists-helper : (Listof Any) -> Number) 
(define (count-3lists-helper l) 
    (cond [(= (length l) 3) 1] 
     [else 0])) 

(: length : (Listof Any) -> Number) 
(define (length l) 
    (cond 
     [(null? l) 0] 
     [else (add1 (length (rest l)))])) 

我得到的错误是:

. Type Checker: Polymorphic function `first' could not be applied to 
arguments: 
Types: (Pairof a (Listof b)) -> (a : ((! False @ (car) (0 0)) | (False @ (car) (0 0))) : (car (0 0))) 
     (Listof a) -> a 
Arguments: (Pairof Any (Listof Any)) 
Expected result: (Listof Any) 
in: (first l) 
+0

错误发生是因为在count-3lists的定义中,表达式'(first l)'具有类型'Any',但它在上下文中,因为“count-3lists-helper”的参数,期望有一个“(Listof Any)”。但是,这个问题并不在你的'长度'功能中。你有没有试过把你的'长度'函数放在一个单独的文件中? –

回答

2

好像你希望你的count-3lists功能采取的列表作为其输入的列表。现在你有(Listof Any)

你想要表达的东西像(ListofList),但内部列表必须是一个东西的列表,所以你可以写为(Listof (Listof Any))

那么你的代码的第一部分变成这样:

(: count-3lists : (Listof (Listof Any)) -> Number) 
(define (count-3lists l) 
    (cond 
    [(null? l) 0] 
    [else (+ (count-3lists-helper (first l)) (count-3lists (rest l)))])) 

之后,你的代码的其余部分工作。事实证明,你的length功能很好。 (所以你应该重新命名你的问题。)