æ¨æ¥ã®コパスタの会ã§ã³ã¢ããã®èª¬æããããReaderã³ã¢ããï¼å¤§åå¤æ°ãåç §ããã³ã¢ããï¼ãç»å ´ãããã§ããHaskellã§ã¯Stateã¢ãããReaderã¢ãããã³ã¢ããã§ãªããã¢ããã§å®è£ ããã¦ãã®ã¯ä½æ ï¼ãã¨ãã話ã«ã
ãã®ã¨ãã¯ããMonadStateã¯ã©ã¹ã® get ã¨ããMonadReaderã¯ã©ã¹ã® ask ã¨ããäºå®ä¸ã³ã¢ãããä½ã£ã¦ãããããªãããªããã¨ããç´ç²ãªã¢ããã«ã¯ãªããªãããããã¨ã話ãã¦ã訳ã§ããã
確ããã¦ã¿ãããReaderã¢ããã¯ã¡ããã¨ã¢ããã«ãªã£ã¦ã¾ããã
⻠以ä¸ãã³ãã¹ã¿ã®ä¼åºå¸è
åãããã®è¾ºã®ç¥èãå¤å°åæããã以ä¸ã®è¨èãè£ãæ°åã¨æéãç¾å¨ãªãã®ã§ã¨ããããâ¦
Haskellã³ã¼ãã§æ¸ãã¦ã¿ã
ä¾ãã°ã次ã®ãããªé¢æ°f, gããã£ãã¨ãã¾ããsã¯å¤§åå¤æ°ã
f (a, s) = a + s g (b, s) = b * s
ãã®2é¢æ°ãã³ã¢ããä¸ã§åæãã㨠(f;g) (a, s) = (a + s) * s ã®ãããªæãã«ãªãã¨æå¾ ã§ãã¾ãã
(f;g) (2, 3) => (2 + 3) * 3 => 15
ã§ããã®2é¢æ°ãHaskellã®Readerã¢ããã§ã¯ãããªé¢¨ã«æ±ãã¾ãã
import Control.Monad.Reader curry_f a = Reader $ \s -> (a + s) curry_g b = Reader $ \s -> (b * s) f_g a = (return a) >>= curry_f >>= curry_g
f_g ã¯ããã£ãã® f 㨠g ã®ããã®ã¢ããä¸ã§ã®åæã§ãã
f,gã«å¯¾ãã¦ä¸æ¦ã«ãªã¼åï¼ããããã¨ï¼ãããã®ããã¤ã³ããaskã¨ããå®ã¯å
¨ç¶ä½¿ããªãã¦ãOKã§ããã
f_gã®å®è¡çµæãrunReader ã¯ãReaderã¢ããï¼ããã§ã¯ã(f_g 2)ï¼ã«å¤§åå¤æ°ã®å¤ï¼ããã§ã¯3ï¼ãã»ãããã¦ãæçµçãªçµæãæ±ãã¾ãã
*Main> runReader (f_g 2) 3 -- (2 + 3) * 3 15
ãçµµãããã¦ã¿ã
å
ã®ã³ã¢ããã¨ã対å¿ãããã®ã¢ããã®æ§åããçµµããããã¨ããããªæãã«ããã¤ã³ãï¼ãã¦ã¹ã§ããã£ã¨æ¸ããã®ã§è¦ãç®ãã¤ãã¤ããªã®ã¯ç®ãã¤ã¶ã£ã¦ãã ãã⦠å³ãã³ã¢ãããå·¦ã対å¿ããã¢ããã
ã¤ã¾ããå ã®ã³ã¢ããå ã®é¢æ°ã f: A à S â B ã ã£ãã¨ããããf^: A â (S â B) ã¨ã«ãªã¼åãã¦ãã¾ã£ã¦ããã®ã«ãªã¼åãããã®ãã¢ããã§æ±ãã¾ããBãã¡ã¤ã³ã¹ããªã¼ã ã®åºåãSãå¯ä½ç¨çãªãåºåãã«ãªã£ã¦ãã®ã§ãã
é¢ç½ãã¨ããã¯ããã®Sã¯å®ã¯ãåºåãã®ããªããããå
¥åã(ï¼)ã§ãå³å³ã®Sã®ã©ã¤ã³ï¼å³ä¸ã§ã¯S*ã£ã¦æ¸ãããã©ï¼ã¯ãå®ã¯æ¬æ¥ã®åãã¨ã¯éåãï¼ä¸ããä¸ã¸ã®ãã¼ã¿ã®æµãï¼ã«ãªã£ã¦ããã§ããã
ã§ãSã®åæµç¹ï¼ã¹ã¿ã³ãã³ã°ã¢ããã§ã¯ã¢ãã¤ãæ¼ç®ãæç«ããã¨ããï¼ã¯ãå®ã¯ä¸ããä¸åãã«ãSã®å¤ãã³ãã¼ãã¦ã¾ããä¸èº«ã¯ã³ã¢ããã®å¯¾è§åã¨åãã
ãããªæãã§äºå®ä¸ã大åå¤æ°åç
§ã³ã¢ããã¨ãåãäºãã¢ããã®æ çµã¿ã§å®ç¾ãã¡ãã£ã¦ãâ¦ããã§ãã
ã§ãæ¹ãã¦æ¸ãã¾ããããStateã¢ãããåããããªããªãã¯ã使ã£ã¦ã¾ãã
追è¨ï¼ã¡ããã¨ã¢ãããèãã¦ã¿ãï¼æ¸ãããï¼
ãã®Readerã¢ãã T 㯠T = (-)S ã¨ãã«ãªã£ã¡ãããã§ãããã¢ããã®åæ μ: T2=T;TâT ã¯è¦ã¯ (-)SS â (-)S ã¨ãSã®Sä¹ãSã«ãªããããªèªç¶å¤æãããã£ã¡ã ã¼äºã«ãªãã¾ãã
ã¿ã¥ããã®ã§ XS ã (X^S) ã¨æ¸ããã¨ã«ããã¨ã(X^S)^S ã X^(S^S) ï¼ååï¼ã¨ãããã¨ãã¾ããã¯ãªæ³åãæãç«ã£ã¦ãããã°ãã¹ã(^)ãä¹æ³ã¨ããã¢ãã¤ãã«ããã¹ã¿ã³ãã³ã°ã¢ããã«ãªãã®ã«â¦ã¨æã£ããã