Passing lambdas ("closures") as params - type?


#1

Here’s what I’m trying to achieve in Typescript syntax:

function find<T>(
    predicateFunc: (object: T) => Boolean,
    arrays: Array<T>
) {
    ...
   arrays.forEach( function(elem){ 
      predicateFunc(elem)
   })
}

I’m wondering if I can define a type " (object: T) => Boolean " in skookumscript,
AND have a function receive another function as input…
(if it can, than skookumscript can be considered as functional language)

Thanks!


#2

Sure, that routine basically already exists as List.any?() or List.find?().

Here is an example of how you would do it in script form.

// Adding as find() in the List class
( // Pass in a closure that takes an item and returns a Boolean
  (ItemClass_ item) Boolean test
) Boolean
  [
  // Iterate through this list and stop on first item that has
  // `test` return true
  any?(test)
  ]

[You can use the SkookumIDE to see the code for List.any?() if you are interested in how to implement it.]

Then you would call it with code such as:

{1 3 5 8 9}.find[item.pow2?]  // true - found 8
{1 3 5 8 9}.find[item = 42]   // false - did not find 42

It is easy to do many functional forms of coding with SkookumScript. :madsci: