Pascal is my study language and I am curious whether C# also has the functions pred
and succ
.
This is what I have done in Pascal that I want to try in C#
// in Pascal:
pred(3) = 2
succ(False) = True
pred('b') = 'a'
type enum = (foo, bar, baz);
succ(bar) = baz; pred(bar) = foo
Is the same code applicable for C#, too? If so, what is the namespace for these functions?
(I searched Google, but couldn't find the answer)
There aren't pred
and succ
functions in C#. You just write n - 1
or n + 1
.
You can use ++ or -- operator:
3++ = 4
3-- = 2
Not sure why you would need it though when you can just do 3+1 or 3-1 :)
You have method overloading in c# so it's easy to have pred and succ, You can do it by:
public int pred(int input)
{
return input - 1;
}
public char pred(char input)
{
return (char)((int)input - 1);
}
....
Using extensions:
public static int Pred(this int self) => self - 1;
public static int Succ(this int self) => self + 1;
Then, this would work:
3.Pred() //-> 2
int x = 3;
x.Succ() //-> 4
Probably not considered very idiomatic, but still works. Would have to override for other integer types (like short
). Check if the calls get inlined if you're concerned with performance.
Note: ++
and --
act as Inc
and Dec
, not Succ
and Pred
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.