【问题标题】:How to construct a macro emitting arbitrary number of possible matches?如何构造一个发出任意数量可能匹配的宏?
【发布时间】:2013-01-08 15:01:26
【问题描述】:

假设我想创建一个这样的宏:

m(1, k) 会产生:

match(k)
{
  | 1 => 2
  | _ => 0
}

m(2, k) 会产生:

match(k)
{
  | 1 => 2
  | 2 => 3
  | _ => 0
}

等等。尽管接受了可能匹配的<[ $i => $(i + 1) ]> 之类的构造,但我不知道如何创建由这些组成的匹配表达式。这个例子当然是人为的;)

【问题讨论】:

    标签: metaprogramming nemerle


    【解决方案1】:
    public macro m(to, k)
    {
      def toInteger(literal)
      {
         | <[ $(i : int) ]> => i
         | _ => Message.Error(literal.Location, $"'$literal' integer literal expected"); 0;
      }
    
      def to = toInteger(to);
    
      def createCases(i) 
      {
         | i when (i > 0) => <[case: | $i => $(i + 1)  ]> :: createCases(i - 1);
         | _ => [ <[case: | _ => 0 ]> ]
      }
    
      <[
        match ($k)
        {
          ..$(createCases(to))
        }
      ]>
    }
    

    http://nemerle.org/Macros_tutorial#Matching_match-cases

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      相关资源
      最近更新 更多