我在Racket中遇到了这个任务5天,有人知道我该如何处理它?
给定arity 2的函数和n
元素的列表,返回所有元素的字符串函数的评估,例如:
>(reduce + '(1 2 3 4 5 6 7 8 9 10))
55
> (reduce zip '((1 2 3) (4 5 6) (7 8 9)))
'((1 (4 7)) (2 (5 8)) (3 (6 9)))
答案 0 :(得分:12)
你走了。
(define (reduce func list)
(assert (not (null? list)))
(if (null? (cdr list))
(car list)
(func (car list) (reduce func (cdr list)))))
试验:
> (reduce + '(1 2 3 4 5 6 7 8 9 10))
55
> (reduce zip '((1 2 3) (4 5 6) (7 8 9)))
((1 (4 7)) (2 (5 8)) (3 (6 9)))
为了完整性,zip
的实现(假设有两个列表并且列表长度相同)是:
(define (zip l1 l2) (map list l1 l2))
答案 1 :(得分:6)
您可以使用foldl
:
(define (reduce f xs)
(and (not (empty? xs)) (foldl f (first xs) (rest xs))))
答案 2 :(得分:0)
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
var checked = [Bool]()
let section = ["Science", "Math"]
let items = [["Physics", "Biology", "Chemistry"], ["Algebra I", "Algebra II", "Statistics"]]
override func viewDidLoad(){
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.allowsMultipleSelection = true
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.items[section].count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
// #warning Incomplete implementation, return the number of sections
return self.section.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return self.section[section]
}
//All before.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
//MARK: -Checkmark and save support.
cell.accessoryType = cell.isSelected ? .checkmark : .none
cell.selectionStyle = .none // to prevent cells from being "highlighted"
return cell
}
//MARK: - Checkmark and save functions.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
//MARK: - Sections
}