简体   繁体   English

定义列表中的数字是否小于参数 - Scala

[英]Define if numbers in list are less than one in parameter - Scala

Write a function which at the input takes two parameters: a list of integers and a number.编写一个 function,它的输入有两个参数:一个整数列表和一个数字。 The output returns a logical value. output 返回一个逻辑值。 The function returns "true" if all numbers in the list are smaller than the number given in the second parameter.如果列表中的所有数字都小于第二个参数中给出的数字,则 function 将返回“true”。 Otherwise, the function returns "false".否则,function 返回“false”。

My code:我的代码:

def less [A](list:List[A], number:Int):Boolean =
  if (list == Nil) false
  else ((List.head < number) && less[A](list:List.tail, number:Int))


less(List(1, 2, 3, 4), 5)
less(List(6,1,2,3),6)

Error message in IntelliJ: IntelliJ 中的错误消息:

On line 3: error: value head is not a member of object List第3行:错误:值头不是object列表的成员

else (List.head < number) && less[A](list:List.tail, number:Int) //2 else (List.head < number) && less[A](list:List.tail, number:Int) //2

^ ^

On line 3: error: type tail is not a member of object List第 3 行:错误:尾类型不是 object 列表的成员

My question: What should I improve in this code to have it working?我的问题:我应该在这段代码中改进什么才能让它工作?

Seems an awful lot like home work...看起来很像家庭作业...

Scala has a forall function that can test a predicate against all values in the collection and returns a Boolean . Scala 有一个forall function 可以针对集合中的所有值测试谓词并返回Boolean

def less(xs: List[Int], number: Int) = xs.forall(x =>???)

I think you want something like this:我想你想要这样的东西:

def less (list:List[Int], number:Int):Boolean =
  if (list == Nil) true
  else ((list.head < number) && less(list.tail, number))


less(List(1, 2, 3, 4), 5)//true
less(List(6,1,2,3),6)//false

But you should just use forall like @Brian said但是你应该像@Brian说的那样使用forall

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM