在球拍中定义一个接受列表列表的函数
Defining a function that accepts a List of Lists in racket
我的任务是计算我的列表(List of List)中有多少个长度为 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)
您似乎希望 count-3lists
函数将列表的列表作为其输入。现在你有 (Listof Any)
。
你想要的是表达类似(Listof List)的东西,但是内部列表必须是一些东西的列表,所以你可以把它写成(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
功能没问题。 (所以你应该重命名你的问题。)
我的任务是计算我的列表(List of List)中有多少个长度为 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)
您似乎希望 count-3lists
函数将列表的列表作为其输入。现在你有 (Listof Any)
。
你想要的是表达类似(Listof List)的东西,但是内部列表必须是一些东西的列表,所以你可以把它写成(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
功能没问题。 (所以你应该重命名你的问题。)