0

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

m(1, k)会产生:

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

m(2, k)会产生:

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

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

4

1 回答 1

2
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

于 2013-01-09T09:17:33.120 回答