好吧,它不是很短,但我还是发布它,只是为了好玩......
请注意,与大多数其他答案不同,此答案不使用eval
,因为它在 C# 中不可用(使用它会短得多)
C#,729 个字符
using System;using System.Linq;using w=System.Double;class Op{public char c;public int p;public Func<w,w,w>f;}class Program{static void Main(string[]p){var nb=p.Select((n,i)=>new{n=w.Parse(n),i});var op=new[]{new Op{c='+',p=0,f=(a,b)=>a+b},new Op{c='-',p=0,f=(a,b)=>a-b},new Op{c='*',p=1,f=(a,b)=>a*b},new Op{c='/',p=1,f=(a,b)=>a/b},};Func<Op,Op,Func<w,w,w,w>>fg=(o1,o2)=>(x,y,z)=>o1.p>=o2.p?o2.f(o1.f(x,y),z):o1.f(x,o2.f(y,z));Func<w,w>nan=d=>w.IsInfinity(d)?w.NaN:d;var res=from o1 in op from o2 in op from x in nb from y in nb where x.i!=y.i from z in nb where z.i!=x.i&&z.i!=y.i let r=nan(fg(o1,o2)(x.n,y.n,z.n))select string.Format("{0}{1}{2}{3}{4}={5:F0}",x.n,o1.c,y.n,o2.c,z.n,r);res.ToList().ForEach(Console.WriteLine);}}
扩展版
using System;
using System.Linq;
using w=System.Double;
// Operator class
// c = character
// p = priority
// f = function
class Op { public char c; public int p; public Func<w, w, w> f; }
class Program
{
static void Main(string[] args)
{
// Parse the input and associate each number with its index
var nb = args.Select((n, i) => new { n = w.Parse(n), i });
// Operators definition
var op = new[]
{
new Op { c = '+', p = 0, f = (a, b) => a + b },
new Op { c = '-', p = 0, f = (a, b) => a - b },
new Op { c = '*', p = 1, f = (a, b) => a * b },
new Op { c = '/', p = 1, f = (a, b) => a / b },
};
// Function generator to compute the result ; handles operator priority
Func<Op, Op, Func<w, w, w, w>> fg =
(o1, o2) =>
(x, y, z) =>
o1.p >= o2.p
? o2.f(o1.f(x, y), z)
: o1.f(x, o2.f(y, z));
// Converts +/- Infinity to NaN
Func<w, w> nan = d => w.IsInfinity(d) ? w.NaN : d;
// Results
var res =
// Combinations of 2 operators
from o1 in op
from o2 in op
// Permutations of numbers
from x in nb
from y in nb
where x.i != y.i
from z in nb
where z.i != x.i && z.i != y.i
// Compute result
let r = nan(fg(o1, o2)(x.n, y.n, z.n))
// Format output
select string.Format("{0} {1} {2} {3} {4} = {5:F0}", x.n, o1.c, y.n, o2.c, z.n, r);
res.ToList().ForEach(Console.WriteLine);
}
}
谁说你不能在 C# 中进行函数式编程?;)
编辑:修复以使其与重复的数字一起使用