473,785 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing a simple function in C#


I am trying to learn C# and .NET programming in general but I am finding it
very hard going. To start with, I'd like to translate some trivial
functions from other languages that I am familiar with into C#.

Here is a simple function in OCaml that nests "n" applications of "f"
around "x", with "n" defaulting to "n=2":

let rec nest ?(n=2) f x = if n=0 then x else nest ~n:(n-1) f (f x)

For example, "nest f x" gives "f(f(x))" and "nest ~n:3 f x"
gives "f(f(f(x))) ".

I am unable to write this elegantly in C#. This is the best I've come up
with and it doesn't even support partial application (currying):

class Program
{
abstract class Nest<T>
{
int n;

public Nest()
{
n = 2;
}

public abstract T f(T x);

public T Apply(T x)
{
while (n 0)
{
x = f(x);
--n;
}

return x;
}

public int N
{
get
{
return n;
}

set
{
n = value;
}
}
}

class NestTwice : Nest<int>
{
public override int f(int x)
{
return 2 * x;
}
}

static void Main(string[] args)
{
NestTwice nestTwice = new NestTwice();
nestTwice.N = 3;
System.Console. WriteLine(nestT wice.Apply(2));
}
}

So I've implemented the higher-order function "nest" as an abstract base
class "Nest" that you must derive from and override the "f" member
function. The optional argument "n" in the OCaml is implemented as a
mutable property "N" with its default value set to 2 by the constructor.

The "NestTwice" class derives from the "Nest" class, specialized to the
type "T=int", and implements the "f" member such that it doubles its
integer argument.

The main program then constructs an object of the class "NestTwice" , sets
its property "N" to 3, overriding its default value of 2, and calls
the "Apply" method to compute the equivalent of "nest n f".

Needless to say, there are many aspects of this that I am not happy with!

1. Can the handling of the function argument "f" be written more elegantly
(but still generically) in terms of delegates? I'd like to replace my
C++-style abstract "Nest" class with something like:

public static T nest<T>(int n, Delegate<T, Tf, x) {
while (n>0) { x=f(x); --n; }
return x;
}

2. My handling of optional arguments is hideous. Can this be done without
mutation, i.e. without first setting the option to its default and then
altering it to the specified value?

3. Is there a simpler way of getting the return value of a function with
optional arguments than making up a "standard" member called "Apply" and
giving it the non-optional arguments after the optional ones have settled
to their true values?

4. Can the "Nest" class be derived from a statically-typed delegate class?

5. Did I miss something fundamental in C#: can any of this be written more
succinctly or elegantly in C#?

6. Are there any tools that can help by autogenerating code like this? Are
there any .NET languages that can do this as elegantly as OCaml?

My motivation is largely to write better F# code rather than C# but both
languages have the same implementation of optional arguments, so the F#
equivalent of the OCaml one-liner also entails a page of classes, mutation
etc.

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 24 '07 #1
8 5536
Jon Harrop <jo*@ffconsulta ncy.comwrote:

<snip>

Rather than answer each of the questions in turn, here's how I'd
implement it:

delegate T Mutator<T>(T t);

static T Mutate<T>(Mutat or<Tmutator, T initial, int times)
{
for (int i=0; i < times; i++)
{
initial = mutator(initial );
}
return initial;
}

static T Mutate<T>(Mutat or<Tmutator, T initial)
{
return Mutate(mutator, initial, 2);
}

Points to note:
1) Use a generic delegate instead of overriding. Apart from
anything else, this makes life a lot simpler when anonymous methods
are available
2) There's no real need for a separate class with state
3) Use overloading to provide optional parameters
4) Use a for loop instead of while to be idiomatic
5) Boy is it shorter ;)
Your complete program (which doesn't use the default number of
iterations) becomes:

delegate T Mutator<T>(T t);

class Test
{
static T Mutate<T>(Mutat or<Tmutator, T initial, int times)
{
for (int i=0; i < times; i++)
{
initial = mutator(initial );
}
return initial;
}

static void Main()
{
int result = Mutate(delegate (int x) { return x*2; }, 2, 3);
System.Console. WriteLine (result);
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 24 '07 #2
Something like:

namespace Foo

{

public partial class Foo : Form

{

public delegate T Funct<T>(T x);

private void startButton_Cli ck(object sender, EventArgs e)

{

int s = apply(delegate( int x) { return x +5; },

1, 4);

}

public T apply<T>(Funct< Tfunct, T arg, uint timesApply)

{

if (timesApply <= 1)

return funct(arg);

else return (apply(funct,

apply(funct, arg, timesApply-1), 1));

}

}

}

wherein the function of adding 5 to an argument is applied 4 times, to the
argument 1, in the method startButton_Cli ck.

However, this does not address optional parameters, which I do not
understand. If the intent is to to default the timesApply to (say 2), you
could define another apply with only 2 parameters, which just invokes the
one with 3 parameters, passing "2" as the third argument. If the intent is
to have the delegate, Funct, have optional arguments, but of differing types
then I don't see that you can do this since C# is strongly typed. You could
define the delegate to take a list of parameters, all of the same type
(possibly Object), I suppose. I don't understand point 3. Perhaps I
addressed points 4 and 5 to some extent. As for point 6, C# does not have a
macro feature, so cannot generate code. Some, but not nearly all, of this
functionality can be duplicated at runtime via generics.

Since all functions in C# must be in some class, it does not map to a purely
functional language. However, the class Foo is arbitrary, and I don't see
that you need to subclass it (but it probably this has something to do with
optional parameters, which I don't understand). Note that Foo itself is not
a generic class. That would give you another level of genericness, but I
don't see what purpose it would serve.

Perhaps this helps; sorry if I have missed some of your points.



"Jon Harrop" <jo*@ffconsulta ncy.comwrote in message
news:46******** **************@ ptn-nntp-reader02.plus.n et...
>
I am trying to learn C# and .NET programming in general but I am finding
it
very hard going. To start with, I'd like to translate some trivial
functions from other languages that I am familiar with into C#.

Here is a simple function in OCaml that nests "n" applications of "f"
around "x", with "n" defaulting to "n=2":

let rec nest ?(n=2) f x = if n=0 then x else nest ~n:(n-1) f (f x)

For example, "nest f x" gives "f(f(x))" and "nest ~n:3 f x"
gives "f(f(f(x))) ".

I am unable to write this elegantly in C#. This is the best I've come up
with and it doesn't even support partial application (currying):

class Program
{
abstract class Nest<T>
{
int n;

public Nest()
{
n = 2;
}

public abstract T f(T x);

public T Apply(T x)
{
while (n 0)
{
x = f(x);
--n;
}

return x;
}

public int N
{
get
{
return n;
}

set
{
n = value;
}
}
}

class NestTwice : Nest<int>
{
public override int f(int x)
{
return 2 * x;
}
}

static void Main(string[] args)
{
NestTwice nestTwice = new NestTwice();
nestTwice.N = 3;
System.Console. WriteLine(nestT wice.Apply(2));
}
}

So I've implemented the higher-order function "nest" as an abstract base
class "Nest" that you must derive from and override the "f" member
function. The optional argument "n" in the OCaml is implemented as a
mutable property "N" with its default value set to 2 by the constructor.

The "NestTwice" class derives from the "Nest" class, specialized to the
type "T=int", and implements the "f" member such that it doubles its
integer argument.

The main program then constructs an object of the class "NestTwice" , sets
its property "N" to 3, overriding its default value of 2, and calls
the "Apply" method to compute the equivalent of "nest n f".

Needless to say, there are many aspects of this that I am not happy with!

1. Can the handling of the function argument "f" be written more elegantly
(but still generically) in terms of delegates? I'd like to replace my
C++-style abstract "Nest" class with something like:

public static T nest<T>(int n, Delegate<T, Tf, x) {
while (n>0) { x=f(x); --n; }
return x;
}

2. My handling of optional arguments is hideous. Can this be done without
mutation, i.e. without first setting the option to its default and then
altering it to the specified value?

3. Is there a simpler way of getting the return value of a function with
optional arguments than making up a "standard" member called "Apply" and
giving it the non-optional arguments after the optional ones have settled
to their true values?

4. Can the "Nest" class be derived from a statically-typed delegate class?

5. Did I miss something fundamental in C#: can any of this be written more
succinctly or elegantly in C#?

6. Are there any tools that can help by autogenerating code like this? Are
there any .NET languages that can do this as elegantly as OCaml?

My motivation is largely to write better F# code rather than C# but both
languages have the same implementation of optional arguments, so the F#
equivalent of the OCaml one-liner also entails a page of classes, mutation
etc.

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet

May 24 '07 #3
Jon Skeet [C# MVP] wrote:
Points to note:
1) Use a generic delegate instead of overriding. Apart from
anything else, this makes life a lot simpler when anonymous methods
are available
Ingenious.
2) There's no real need for a separate class with state
Yes. That was a C++ism.
3) Use overloading to provide optional parameters
I'm concerned that this doesn't scale to having more optional arguments.
4) Use a for loop instead of while to be idiomatic
Right.
5) Boy is it shorter ;)
Wonderful. Thanks for the help!

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 25 '07 #4
Jon Harrop <jo*@ffconsulta ncy.comwrote:
3) Use overloading to provide optional parameters

I'm concerned that this doesn't scale to having more optional arguments.
When you've got lots of related parameters, encapsulate them into a
class on their own, with default values.

See
http://www.yoda.arachsys.com/csharp/...ermanager.html
for an example of this.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 25 '07 #5
On May 25, 9:20 am, Jon Skeet [C# MVP] <s...@pobox.com wrote:
Jon Harrop <j...@ffconsult ancy.comwrote:
3) Use overloading to provide optional parameters
I'm concerned that this doesn't scale to having more optional arguments.

When you've got lots of related parameters, encapsulate them into a
class on their own, with default values.

Seehttp://www.yoda.arachs ys.com/csharp/miscutil/usage/buffermanager.h tml
for an example of this.

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Hi,

Furthermore,
Use the Command Design Pattern to encapsulate lot's of parameters.

Moty

May 25 '07 #6
"Jon Harrop" <jo*@ffconsulta ncy.comwrote in message
news:46******** **************@ ptn-nntp-reader02.plus.n et...
>
Ingenious.
Yep.
Jon does stuff like this all the time. It's almost scary...

- Michael S
May 25 '07 #7
Moty Michaely wrote:
Use the Command Design Pattern to encapsulate lot's of parameters.
Can you elaborate on this?

I've read this description of the pattern:

http://www.exciton.cs.rice.edu/JAvaR...ns/command.htm

and I can't see how it is relevant. Is this for when you have a set of
optional arguments that are common to several different functions?

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 26 '07 #8
On May 26, 4:59 am, Jon Harrop <j...@ffconsult ancy.comwrote:
Moty Michaely wrote:
Use the Command Design Pattern to encapsulate lot's of parameters.

Can you elaborate on this?

I've read this description of the pattern:

http://www.exciton.cs.rice.edu/JAvaR...ns/command.htm

and I can't see how it is relevant. Is this for when you have a set of
optional arguments that are common to several different functions?

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journalhttp://www.ffconsultan cy.com/products/fsharp_journal/?usenet
Hi,

When you need to pass common arguments (not necessarily optional) you
can encapsulate the arguments with a class and implement a function in
that class..

For example (very simple one, you can always elevate it to much more
complex one):

To copy a file we can do this:
void CopyFile(string src, string dest)

Or we can encapsulate the CopyFile operation to a FileOperation class:

class FileOperationCo ntext
{
string source;
string destination;

public FileOperationCo ntext(string source, string destination)
{
this.source = source;
this.destinatio n = destination;
}

}

abstract class FileOperation {
FileOperationCo ntext context;

public FileOperation(F ileOperationCon text context)
{
this.context = context;
}

void Operate();
}

class FileCopy : FileOperation
{
public FileCopy (FileOperationC ontext context) : base(context)
{ }

override Operate() {
System.IO.File. Copy(context.so urce, context.destina tion);
}
}

You can of course not implement methods and just use the class as an
argument list..
for example:

void CopyFile(FileOp erationContext context) {
System.IO.File. Copy(context.so urce, context.destina tion);
}

void MoveFile(FileOp erationContext context) {
System.IO.File. Move(context.so urce, context.destina tion);
}

etc....

Hope this clears things up.. =)

Moty

May 26 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2085
by: Mark Stijnman | last post by:
A while ago I posted a question about how to get operator behave differently for reading and writing. I basically wanted to make a vector that can be queried about whether it is modified recently or not. My first idea, using the const and non-const versions of operator, was clearly not correct, as was pointed out. Julián Albo suggested I could use proxies to do that. I've done some googling for proxies (also in this group) and personally,...
385
17316
by: Xah Lee | last post by:
Jargons of Info Tech industry (A Love of Jargons) Xah Lee, 2002 Feb People in the computing field like to spur the use of spurious jargons. The less educated they are, the more they like extraneous jargons, such as in the Unix & Perl community. Unlike mathematicians, where in mathematics there are no fewer jargons but each and every one are
7
2442
by: beza1e1 | last post by:
I'm writing a parser for english language. This is a simple function to identify, what kind of sentence we have. Do you think, this class wrapping is right to represent the result of the function? Further parsing then checks isinstance(text, Declarative). ------------------- class Sentence(str): pass class Declarative(Sentence): pass class Question(Sentence): pass class Command(Sentence): pass
2
1769
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start populating only the fields with value in specified locations(3 seperate structures). The way the C does is by creating a structures, which will be filled with null initially. Then selectivly populating only the fields with values and only up to the length...
6
1293
by: cdecarlo | last post by:
Hello, I've often found that I am writing little scripts at the interpretor to read a text file, perform some conversion, and then write the converted data back out to a file. I normally accomplish the above task by reading the lines of the entire file into a list, preforming some function to that list and then writing the list back out. I want to write a generic function/module that will free me from repeatedly typing the same thing,...
22
2723
by: JoeC | last post by:
I am working on another game project and it is comming along. It is an improvment over a previous version I wrote. I am trying to write better programs and often wonder how to get better at programming. I tend to learn what is useful and gets the job done. I am always curious if there is some techique I don't know. I read books and study as well as write programs. My goal is to some day be able to get a job programming. I have a...
9
2099
by: jerry.upstatenyguy | last post by:
I am really stuck on this. I am trying to write a string array containing a "word" and a "definition" to a class called Entry. Ultimately this will end up in another class called dictionary. No, this is not a homework assignment. In fact it was a question on my class midterm that everyone bombed. Unfortunately we never covered this in class prior to the midterm. Anyway, please help if you would be so kind. Here is what I have. I...
10
2138
by: Phillip Taylor | last post by:
Hi guys, I'm looking to develop a simple web service in VB.NET but I'm having some trivial issues. In Visual Studio I create a web services project and change the asmx.vb file to this: Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel <System.Web.Services.WebService(Namespace:="http:// wwwpreview.#deleted#.co.uk/~ptaylor/Customer.wsdl")_
0
11274
ashitpro
by: ashitpro | last post by:
Writing System Call Wrappers in User Space. Recently I saw a post in Linux/Unix section to know the user who deleted the file in linux. Currently there is nothing in linux which could achieve this. There are certain tools which profiles the activities on file system, but none of these provides the particular user information. Main task for all these tools to check the performance of the system. First I thought why not to hook the unlink...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6737
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.