codecamp

Lambdas实例

在这里你可以找到一些lambda表达式的变种。

Parenthesis

如果它是一个单一的非类型化参数,可以省略括号。否则,parenthesis是必需的。

<?hh

namespace Hack\UserDocumentation\Lambdas\Examples\Examples\SyntaxExamples;

function addLastname(): Vector<string> {
  $people = Vector {
      "Carlton",
      "Will",
      "Phil"
  };
  // You need parentheses when adding a type annotation or default value
  $annotatedArgument = (string $name) ==> $name . " Banks";
  $annotatedReturnType = ($name): string ==> $name . " Banks";
  $defaultValue = (string $name = "Ashley") ==> $name . " Banks";

  // You could use any of the above closures.
  return $people->map($annotatedReturnType);
}

function calculateYears(): int {
  // You need parentheses when using more than one argument
  $difference = ($start, $end) ==> $end - $start;
  return $difference(1990, 1996);
}

function familySize(): int {
  $people = Vector {
      "Carlton",
      "Will",
      "Phil"
  };
  // You can use curly braces to create a compound statement
  $calculateSize = $family ==> {
    $counter = 0;
    foreach ($family as $member) {
      $counter++;
    }
    return $counter;
  };
  return $calculateSize($people);
}

function run(): void {
  var_dump(familySize());
  var_dump(calculateYears());
  var_dump(addLastname());
}

run();

Output

int(3)
int(6)
object(HH\Vector)#4 (3) {
  [0]=>
  string(13) "Carlton Banks"
  [1]=>
  string(10) "Will Banks"
  [2]=>
  string(10) "Phil Banks"
}
Lambdas创立故事
hack类型常量:简介
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }