ã·ã£ãã¼ã¤ã³ã°ã¨ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°
ã·ã£ãã¼ã¤ã³ã°ã®ãªãè¨èªã¨ãã¤ãã¥ã¼ã¿ãã«ä¸å¿ã®ããã°ã©ãã³ã°(以ä¸ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°)ã®ç¸æ§ã£ã¦æªãã®ã§ã¯ï¼ã¨æã£ãã®ã§ããã°ã«æ®ãã¦ããã¾ãã
ã·ã£ãã¼ã¤ã³ã°ã¨ã¯
æ¢åã®å¤æ°ã¨ååã®å¤æ°ãå®ç¾©ãã¦ããã®ã¹ã³ã¼ãã§æ¢åã®å¤æ°ã«ã¢ã¯ã»ã¹ã§ããªãããæ©è½ã§ãã ä¾ãã°ãF#ã§ã¯ã·ã£ãã¼ã¤ã³ã°ãã§ããã®ã§ã
let f x = if x % 2 = 0 then (* å¼æ°ã®xãã·ã£ãã¼ã¤ã³ã° *) let x = -1 printf "%d, " x (* ã¹ã³ã¼ããæããã®ã§ãå¼æ°ã®xã表示 *) printfn "%d" x f 10 (* => -1, 10 *) f 11 (* => 11 *)
ã¨ãªãã¾ãã
ã·ã£ãã¼ã¤ã³ã°ã®ãªãè¨èªãä¾ãã°C#ã§ã¯åããã¨ã¯ã§ããªãã®ã§ãå¥ã®ååãä»ããããåä»£å ¥ã§åé¿ãããã¨ã«ãªãã¾ã*1ã
public void F(int x) { if (x % 2 == 0) { var otherX = -1; Console.Write("{0}, ", otherX); } Console.WriteLine(x); }
ã·ã£ãã¼ã¤ã³ã°ã®ä½¿ãé
ã·ã£ãã¼ã¤ã³ã°ã®ä½¿ãéã¨ãã¦ã¯ãä¾ãã°ä»¥ä¸ã®ãããªãã®ãããã¾ãã
- ãã¥ã¼ã¿ãã«ãªå¤æ°ã®ç¯å²ã®å¶é
- ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ã§ã®ç¶æ å¤æ°ã®åã渡ã
ãã¥ã¼ã¿ãã«ãªå¤æ°ã®ç¯å²ã®å¶é
F#ã«ã¯ãã¥ã¼ã¿ãã«ãªå¤æ°ãããã¾ãã ã§ãããä¸è¬çãªF#ããã°ã©ãã¯æ¥µåãã¥ã¼ã¿ãã«ãªå¤æ°ã使ãã¾ããã ã©ããã¦ããã¥ã¼ã¿ãã«ãªå¤æ°ã使ããããªã£ãã¨ãã¦ããããæç¹ä»¥éã§ã¯åä»£å ¥ãè¡ãããªãã¨åãã£ã¦ãããªãããã¥ã¼ã¿ãã«ãªå¤æ°ãã·ã£ãã¼ã¤ã³ã°ãããã¨ã§ã以éã§èª¤ã£ã¦åä»£å ¥ã§ããªããã¨ãã³ã³ãã¤ã©ã«ä¿è¨¼ããããã¨ãã§ãã¾ãã
let mutable x = 10 (* xã«åä»£å ¥ããå ´åãããã³ã¼ã *) ... (* ããããã¯xã«åä»£å ¥ããªã *) let x = x ...
ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ã§ã®ç¶æ å¤æ°ã®åã渡ã
ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ãã¦ããã¨ãããå¤æ°ãã¯ãã¼ã³ãã¦ä¸é¨åãæ¸ãæããå¤ãä½ãåºãã¨ããã³ã¼ããçµæ§åºã¦ãã¾ãã ãã®ãããªå ´åã«ã·ã£ãã¼ã¤ã³ã°ã使ãã°ãæ´æ°åã®ãããªããªã£ãå¤æ°ã«ã¢ã¯ã»ã¹ã§ããªããªãããå®å¿ãã¦ã³ã¼ãã£ã³ã°ã§ãã¾ãã
let f newKey cache = let cache = cache.Clone(key = newKey) g cache (* ãã®cacheã¯ã·ã£ãã¼ã¤ã³ã°ãããæ¹ã®ãã£ãã·ã¥ *)
ããããã·ã£ãã¼ã¤ã³ã°ã®ãªãè¨èªã§ã¯ããã¯ã§ãã¾ããã ç°¡åã«åããåé¿çã¨ãã¦ã¯ãã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ãä¸é¨æ¨ã¦ã¦ãå¼æ°ã«åä»£å ¥ããããæ°ããååãä»ãããã§ãã
public SomethingResultType F(Cache cache, Key newKey) { var newCache = cache.Clone(key: newKey); return G(newCache); }
ããã¯æ°ããååãä»ããå ´åã§ãã ããããã®å ´åã
public SomethingResultType F(Cache cache, Key newKey) { var newCache = cache.Clone(key: newKey); return G(cache); }
ã®ããã«ééãã¦å ã®å¤æ°ã使ã£ã¦ãã¾ãã¾ãã ã¨ããããä»äºã§å®éã«ä½¿ã£ã¦ãã¾ãã¾ããã ã·ã£ãã¼ã¤ã³ã°ããããã°ãããªãã¹ã¯ãã¾ããã§ãã*2ããåããã®ã表ãã®ã«å¥ã®ååãä»ããªããã°ãªããªãã®ã¯ããããéåæãããã¾ãã
ããä¸æ¹ã®ãåä»£å ¥ãã§åé¿ããæ¹æ³ã¯ãä¸é¨ã¨ã¯ããã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ãæ¨ã¦ããã¨ã«ãªãã®ã§ãä»ã®åé¿çãããå ´åã«åãããã¯ããã¾ããã ãã¾ãã¤ãã¥ã¼ã¿ãã«ã¨ãã¥ã¼ã¿ãã«ãè¡ã£ããæ¥ããããããªãã§ãããã
ã¨ãããã¨ã§ãã·ã£ãã¼ã¤ã³ã°ã®ãªãè¨èªã¯ã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ã¨ç¸æ§ãæªãã®ã§ã¯ãªãã§ããããï¼*3 ã·ã£ãã¼ã¤ã³ã°ããªãè¨èªã§ã¯ãã¤ãã¥ã¼ã¿ãã«ããã°ã©ãã³ã°ãå ¨é¢çã«æ¡ç¨ããã®ã¯ãããããã»ãããããªãã¨ããã®ãç¾æç¹ã§ã®èãã§ãã
*1:ãã ãããããããªãããæ¢åã®å¤æ°ã¨æ°ããå¤æ°ã®åãéãå ´åã¯åä»£å ¥ã§ã¯å¯¾å¿ã§ããªãå ´åããã
*2:typoãã¦ã·ã£ãã¼ã¤ã³ã°ããã¤ãããã§ãã¦ããªãã£ããã¨ãããã¨ãããå¾ã¾ããã»ã»ã»
*3:Stateã¢ããçã使ã£ã¦ç¶æ å¤æ°ãé ãã¨ããã®ãèããããªãã¯ãªãã§ãããã·ã°ããã£å£ãã¡ããã®ã§ããããé¢å