![]() ![]() To create the whilst control structure, define it as a function that takes two parameter groups. The second parameter group appears to return nothing ( Unit), because the last expression in the code block ( i += 1) returns nothing.The first parameter group must evaluate to a Boolean value.I see a function named whilst that has two parameter groups.I demonstrate more examples in this chapter, but the lesson for the moment is that when you see code like this, you should think: ![]() You’ll see this pattern a lot in Scala/FP code, so it helps to get used to it. ![]() These two groups are highlighted in the following image: The second parameter group is the block of code enclosed in curly braces immediately after that. Therefore, by looking at this code you know whilst must be defined so that it’s first parameter group is expecting a Boolean parameter of some sort. Note that this expression yields a Boolean value. The first parameter group is i < 5, which is the expression between the two parentheses. Note: I use a var field here because I haven’t covered recursion yet.Ī thing that your eyes will soon learn to see when looking at code like this is that whilst must be defined to have two parameter groups. To do this, imagine for a moment that you don’t like the built-in Scala while loop - or maybe you want to add some functionality to it - so you want to create your own whilst loop, which you can use like this: var i = 0 To show the kind of things you can do with multiple parameter groups, let’s build a control structure of our own. You must supply the input parameters in three separate input lists.Īnother thing to note is that each parameter group can have multiple input parameters: def doFoo(firstName: String, lastName: String)(age: Int) = ? How to write your own control structures :12: error: too many arguments for method Note that when you write sum with three input parameter groups like this, trying to call it with three parameters in one group won’t work: scala> sum(1,2,3) The rest of this lesson shows the advantages that come from using this approach. That’s all there is to the basic technique. Just put your function’s input parameters in different groups, with each group surrounded by parentheses: def sum(a: Int)(b: Int)(c: Int) = a + b + cĪfter that, you can call sum like this: scala> sum(1)(2)(3) Instead of writing a “normal” add function with one parameter group like this: def add(a: Int, b: Int, c: Int) = a + b + c Writing functions with multiple parameter groups is straightforward.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |