æè¿åã¯ã©ã¹ã¨ããåå¼·ãã¦ããã®ã ããã©ããã®ä¸ã§const
é¢æ°ã¨ããã®ãè¦ã¦æå¿ããã
const
Haskellã ã¨ä»¥ä¸ã®éãã«æ¸ã:
const x _ = x
Scala風ã«æ¸ãï¼ããããã¯Scalaã§æ¸ãã¦ããï¼ã¨ä»¥ä¸ã®éãã«æ¸ã:
def const[A, B](x: A) = (_: B) => x
ã¤ã¾ãã2ã¤ï¼curryingãããï¼å¼æ°ãåãã®ã ããã©ãæåã«åãåã£ãã»ããè¿ãã¦ã2ã¤ç®ã¯æ¨ã¦ã¦ãã¾ãã
const(1)(2) // => 1
ããã ãã ã¨ãã¯ãããã§ããã¨ããæããå¾ ã£ã¦ï¼ã¾ã ã¿ããéããªãã§ï¼
æãç³ã¿é¢æ°ã«å ¥ãã
const
ã®ä½ãé¢ç½ããã£ã¦ãfold
ãreduce
ç³»ã®æãç³ã¿ç³»é¢æ°ã«å
¥ããã¨æªå¥ç¾è±¡ãèµ·ããã¨ãããconst
ã¯2å¼æ°é¢æ°ãªã®ã§ãfold
ãreduce
ã«å
¥ãããã¨ãã§ãããã§ãããã¡ãã£ã¨ãã£ã¦ã¿ã¾ãããã
Haskellã¨éã£ã¦curryingããå½¢ã®ã¾ã¾ã§ã¯ä½¿ããªãã®ã§ãFunction.uncurried
ã使ãå¿
è¦ãããã
val lis = List("ã", "ã", "ã«", "ã", "ã") lis.reduce(Function.uncurried(const)) // => "ã"
reduce
é¢æ°ã«const
ãå
¥ããããæåã®è¦ç´ ãè¿ã£ã¦ããï¼ãªããã¨ããã¨ã
// constãâã¨ããã¦ä¸ç½®è¨æ³ã§æ¸ãã¨â¦â¦ ã â ã â ã« â ã â ã = ((ã â ã) â (ã« â ã)) â ã = (ã â ã«) â ã = ã â ã = ã
ã¨ãªããããreduceLeft
ã§ãreduceRight
ã§ãçµå±æåã®è¦ç´ ãè¿ã£ã¦ãããconst
ã¯çµåå¾ãæºãããããã
(X â Y) â Z = X â Z = X X â (Y â Z) = X â Y = X
const
ã«identity
ã渡ãã¨ãããã«é¢ç½ããã¨ãèµ·ããï¼Scala 3ã§ããã³ã³ãã¤ã«ããªãï¼ã
val cident = const(identity)
lis.reduce(Function.uncurried(cident)) // => "ã"
ãªãã¨æå¾ã®è¦ç´ ãè¿ãããããªãã ãããè¨ç®éç¨ããã©ã£ã¦ã¿ãã¨åããã
const(identity) = _ => identity = _ => x => x
ä»åº¦ã¯2ã¤ç®ã®å¼æ°ãè¿ãé¢æ°ã«ãªã£ãããããããã
ãã¾ã
ã¡ãã£ã¨å®é¨ã ã試ãã«identity
ãäºå渡ãã¦ã¿ããã
val cident2 = const(identity)(identity) cident2(1) // => 1
ãã¼ãã2å¼æ°é¢æ°ã§ã¯ãªããªã£ã¦ãã¾ã£ãã®ã§ãã¡ãã£ã¨æã£ã¦ããã®ã¨éãçµæã«ãªã£ãã
constã«1å¼æ°é¢æ°ãå ¥ããã¨ã2ã¤ç®ã®å¼æ°ã ã使ã2å¼æ°é¢æ°ã«ã§ãã
identity
ã®ã»ãã«ããconst
ã«é¢æ°ãä¸ããã¨ãããã«å¥å¦ãªç¾è±¡ãèµ·ããã
val lis = List("ã", "ã", "ã«", "ã", "ã") val inc = (x: Int) => x + 1 println(lis.foldRight(0)(Function.uncurried(const(inc))) // 5
ãªã¹ãã®é·ããè¿ãããããããããã¯ãåç´ã«Int
ãã¤ã³ã¯ãªã¡ã³ãããé¢æ°ããconst
ã使ã£ã¦2å¼æ°åãããã¨ã§ããªã¹ãã®å
容ãå®å
¨ã«ç¡è¦ãã¦é·ããè¨ç®ãã¦ããã
const
ã«inc
ã渡ãã¨ãæåã®å¼æ°ãè¿ãã®ã§ãconst(inc)(x)(y)
ã¯inc(y)
ã¨çãããªãã
const
ã¯æåã®å¼æ°ãè¿ãé¢æ°ãªã®ã§ãããã«å¼ãæºããã¦ãã¾ãããã«ãªãããconst
ã«1å¼æ°é¢æ°ã渡ãã¨ãæåã®å¼æ°ãç¡è¦ãã¦2ã¤ç®ã®å¼æ°ã渡ãããããã«å¤æããããã¾ãconst
ã2ã¤ç®ã®å¼æ°ãæ¨ã¦ã¦ãããã®ã ããã©ãã«ãªã¼åãã¦ããã®ã§ãå®éã«ä½¿ãããã¨ãã¯1ã¤ç®ã®å¼æ°ãæ¨ã¦ããã¦ããããã«è¦ããã¨ããããªãã¯ã«ãªã£ã¦ãããã ããå³ããç³ã¾ããfoldRight
ã使ãå¿
è¦ããã£ãã®ãï¼
Const
const
é¢æ°ããã¼ã¿æ§é ã®å½¢ã«ããConst
ã¨ãããã®ãèãããã¨ãã§ãã¦ãcatsãªã©ã«å°å
¥ããã¦ããã
case class Const[X, Y](getConst: X)
åY
ã¯ã¾ã£ããã®ããã¼ã§ãååããã«ãã使ããªãã
Const
ã¯Functor
ãApplicative
ã®ã¤ã³ã¹ã¿ã³ã¹ã«ã§ãããããconst
é¢æ°ã®ããä¸è¬åãããå½¢ã¨ãã¦ãã¼ã¿æ§é ã®å¤æãªã©ã«ç¨ããããã
- ä¸ããããé¢æ°
A => B
ãå ¨ãç¡è¦ãã¦åã ãConst[X, A]
ããConst[X, B]
ã«ãããããªfmap
ãä¸ããã°ãConst
ãFunctor
ã«ã§ããã X
ãMonoid
ãªãããã®å®è£ ã使ã£ã¦Const[X, *]
ãApplicative
ã«ã§ãããMonoid
ã®empty
ã使ããã¨ã§pure
ãå®è£ ã§ãããMonoid
ã®combine
ã使ããã¨ã§ap
ãå®è£ ã§ããã
ãããï½ãä½ããããããã¨ããã¨ãfoldMap
ãåæã«å°åºã§ãããããã
ã¯ãªã¹ãã¹ãã¬ã¼ã³ãã¯ããã§æ±ºã¾ãã ãï¼ï¼