Skip to content

Latest commit

 

History

History
81 lines (58 loc) · 1.6 KB

211215.lambdas_blocks_as_arg.md

File metadata and controls

81 lines (58 loc) · 1.6 KB

2021-12-15

https://discordapp.com/channels/918498540232253480/918498540232253483/920610158206414848

YaSH

Can we pass another function as an argument?

erikcorry

You can pass a lambda or a block as an argument, so you have to wrap your function in a lambda or a block.

add x y: return x + y

zip a/List b/List combine/Lambda -> List:

  result := []

  for i := 0; i < a.size; i++:
    value := combine.call a[i] b[i]
    result.add value

  return result

zip a/List b/List [combine] -> List:

  result := []

  for i := 0; i < a.size; i++:
    value := combine.call a[i] b[i]
    result.add value

  return result

main:
  a := [1, 2, 3]
  b := [3, 4, 5]

  lambda_form_of_add := :: | a b | add a b

  block_form_of_add := : | a b | add a b

  print
    zip a b lambda_form_of_add
  
  print
    zip a b block_form_of_add

erikcorry

With a more compact list-creation idiom that would be:

add x y: return x + y

zip a/List b/List combine/Lambda -> List:
  return List a.size: combine.call a[it] b[it]

zip a/List b/List [combine] -> List:
  return List a.size: combine.call a[it] b[it]

main:
  a := [1, 2, 3]
  b := [3, 4, 5]

  lambda_form_of_add := :: | a b | add a b
  block_form_of_add := : | a b | add a b

  print
    zip a b lambda_form_of_add
  print
    zip a b block_form_of_add

And if you didn't need add to be a function at all you could just make a block instead of creating a function and then wrapping it in a block:

zip a/List b/List [combine] -> List:
  return List a.size: combine.call a[it] b[it]

main:
  a := [1, 2, 3]
  b := [3, 4, 5]
  print
    zip a b: | a b | a + b