Write a function which at the input takes two parameters: a list of integers and a number. The output returns a logical value. The function returns "true" if all numbers in the list are smaller than the number given in the second parameter. Otherwise, the function returns "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:
On line 3: error: value head is not a member of object List
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
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.