【发布时间】:2016-05-14 16:47:05
【问题描述】:
如何编写一个函数,该函数构建一个给定长度的列表。通过将 f 应用于元素的索引来确定每个元素:
def buildList[A](length: Int, f: Int => A): List[A]
测试用例是这样的:
test("test") {
def f(x: Int) = x
assert(buildList(10, f) == List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
所以输入示例是 listBuild(10,f) = output List(0,....9)
我知道如何在 OOL 中做到这一点,但功能性编程对我来说是一个新概念。
关于如何做到这一点的任何想法?至少,伪代码会有所帮助..
PS:这不是硬件。我一直在尝试自学 scala,这是我一直在努力解决的功能......
【问题讨论】:
-
I have been trying to teach myself scala and this is a function I have been struggling with...继续 - 我记得 2 年前学习折叠时我的头撞到了墙上 -
"这不是硬件。"如果您这么说,但奇怪的是(至少)你们中的两个人今天就同一功能提出了问题:*.com/questions/35204312/…
-
List.tabulate(length)(f)正是您想要的。但我明白重点是自己写
标签: scala recursion functional-programming