473,378 Members | 1,419 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Predicates, actions and delegates

balabaster
797 Expert 512MB
Okay, after having bashed my head against this long enough I thought of you guys... I thought having exhausted just about every other .NET concept I would come back to predicates because Microsoft's "EndsWithSaurus" demonstration is beyond useless at explaining what this is useful for. Having previously understood delegates and got my head around those, predicates finally makes sense...although I still think Microsoft's example is ridiculous. I still can't make head nor tail of what they would use such an example for...shouldn't you be able to pass a variable into the predicate for the search instead of having to hard-code the search string? Anyway...moving on...

So on to actions...Action<T>: Array.ForEach appears to use Action<T> which is the same conceptually as Predicate<T> except that it now tells us to do something instead of just find out if we've got a match.

I threw a 30 second example together that I thought should work...but for the life of me I can't figure out what I'm missing!

Expand|Select|Wrap|Line Numbers
  1. Function IsPrime(ByVal Data As Integer) As Boolean
  2.   If IsEven(Data) Then Return False
  3.   If Data <= 3 Then Return True
  4.   For i As Integer = 3 To CInt(Math.Sqrt(Data)) Step 2
  5.     If (Data Mod i = 0) Then Return False
  6.   Next
  7.   Return True
  8. End Function
  9.  
  10. Public Sub AddOne(ByVal Data As Integer)
  11.   Data += 1
  12. End Sub
  13.  
  14. Private Sub Main()
  15.  
  16.   'Compose some array of integers
  17.   Dim AllValues() As Integer = New Integer() {1, 3, 5, 6, 8, 9, 10, 12, 13, 15, 17}
  18.   'Grab just the prime numbers from our array
  19.   Dim MyPredicate As New Predicate(Of Integer)(AddressOf IsPrime)
  20.   Dim FilteredValues() As Integer = Array.FindAll(AllValues, MyPredicate)
  21.  
  22.   'Do something with each item in our filtered values list
  23.   Dim MyAction As New Action(Of Integer)(AddressOf AddOne)
  24.   Array.ForEach(Of Integer)(FilteredValues, MyAction)
  25.  
  26.   'Grab our newly modified data
  27.   Dim ModifiedValues() As Integer = FilteredValues
  28. End Sub
So stepping through the code, it would appear that my predicate is running on my array and filtering the primes for me just as I expect...but my action is not adding one to my filtered values...when I get to the end, I would expect modified values to have a list of prime numbers incremented by 1, but instead, I have the list of raw prime numbers.

I'm obviously missing something, but I can't for the life of me see what it is...
Jun 16 '08 #1
7 1488
Plater
7,872 Expert 4TB
Well you pass your parameter "byVal" and expect changes you make inside the function to affect the passed in val.
Don't you need to use "ByRef" or whatever VB calls it?
Jun 16 '08 #2
balabaster
797 Expert 512MB
Well you pass your parameter "byVal" and expect changes you make inside the function to affect the passed in val.
Don't you need to use "ByRef" or whatever VB calls it?
You would think that would be it, and truth be known, I already tried that thinking exactly the same thing, but then I get a compilation error because my action doesn't match the required signature...which doesn't specify which form it should take. I thought maybe if I just removed the byref/byval indicator that it would fix it, but it automatically put it back as byval, compiled and then didn't work.

So yeah...I don't think that's it...any other thoughts?
Jun 16 '08 #3
balabaster
797 Expert 512MB
The more I think about it, the more I wonder what Action<T> was supposed to be used for. It doesn't appear you can do any useful manipulation of data in an array with it. It's sole purpose seems directed towards carrying out some repetitive external action that requires the array data as an input, where 3 lines of code enumerating the array was so horrifying they thought that they absolutely must reduce it to a single line of code (assuming you'd written 5 other lines of code to declare your predicate and your action, or taken the time to understand lamda expressions).

Maybe someone can direct me to a single useful example for the Action<T> class... even the Predicate<T> class seems limited in its use such that if we never had cause to filter an array, there might never be a use for it.

Please someone tell me that I'm missing something because there must've been some greater purpose for Action<T> than spitting out message boxes or writing the contents of an array to a log or the window. I'd like to think that the .NET team weren't asleep at the wheel when this concept was included in the framework...
Jun 16 '08 #4
Plater
7,872 Expert 4TB
Can it return a value?
Jun 17 '08 #5
balabaster
797 Expert 512MB
Can it return a value?
Nope, it doesn't seem to be able to do that.

I've done some more research since I posted this question, and it seems that maybe I missed the purpose of the Action<T> predicate.

It seems that the purpose I presumed it should be of value for, it really isn't, and that was for iterating through the array and somehow modifying the content and returning the modified array - which would be by far the most useful thing it could do in my opinion.

However, it seems that its purpose was misunderstood. It's real purpose appears to be rather for doing some action as a result of the data that is passed in - for instance, writing to an event log, writing to a file, outputting data to screen, populating some class level variable (maybe an array) or doing some other task that requires the data from the array, but cannot modify the data in that array for the purpose of returning the modified data.

Does that make sense?

The example below demonstrates:
Expand|Select|Wrap|Line Numbers
  1. Public Sub WriteToConsole(ByVal Data As String)
  2.   Console.WriteLine(Data)
  3. End Sub
  4.  
  5. Sub Main()
  6.  
  7.   Dim oItems() As String = { _
  8.     "George Washington", _
  9.     "John Adams", _
  10.     "Thomas Jefferson", _
  11.     "James Madison", _
  12.     "James Monroe" _
  13.   }
  14.  
  15.   Array.ForEach(oItems, New Action(Of String)(AddressOf WriteToConsole)
  16.  
  17.   Console.ReadLine()
  18.  
  19. End Sub
Jun 17 '08 #6
Plater
7,872 Expert 4TB
Hmm. Does that effectively create a "Queuing" process that can happen as a background thread?
Like currently for a test project I am reading things that are sent to me over a serial port. It comes in at a decent enough speed.
When I reach a deliminator character I form a message and push it on a queue. Then I have a seperate thread cycling through that Queue object and logging the data to a file.

If that action thing would handle the task of firing an event "when time is avialable" to trigger that log to disk, that would be pretty good.
Jun 17 '08 #7
balabaster
797 Expert 512MB
If that action thing would handle the task of firing an event "when time is avialable" to trigger that log to disk, that would be pretty good.
Alas, it doesn't appear that the Queue object has a ForEach method... I imagine there must be some way to add a hack to it to allow it.

Maybe extend the queue object to implement IEnumerable...if I recall correctly, the IEnumerable interface has a ForEach method which would allow you to implement the action thing...

How I've handled that sort of operation in the past is I add a thread to process the queue with a class level ManualReset switch at the start of the thread. When the thread that posts items to the queue has added an item it sets the manual reset, and when the thread that's reading items from the queue has emptied the queue, it sets the manualreset switch to false. Relatively simple I think.

Thinking about it, I'm not sure you could use the action thing because the queue size would keep changing and you'd get the same error you get when you try to use a for each to delete items from a list.
Jun 20 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Thong Nguyen | last post by:
I wrote my own Predicate class for .NET 1.1 which allowed composite predicates using operator overloading... for example: Predicate p1 = {...}; Predicate p2 = {...}; Predicate p1andp2 =...
0
by: dayzman | last post by:
Hi, M'm writing a program to output the results of transforming logical predicates using deMorgan's. Does anyone know of a library that handles logical predicates? Cheers, Michael
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
1
by: David Veeneman | last post by:
I've been looking at predicate delegates in connection with List<Tsearch methods. My initial reaction is that the mechanism looks cumbersome, to the point where I'm wondering if it's not just...
0
by: bharathreddy | last post by:
Delegates Here in this article I will explain about delegates in brief. Some important points about delegates. This article is meant to only those who already know delegates, it will be a quick...
6
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes...
69
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same...
0
by: raylopez99 | last post by:
Inspired by Jon, I did a demo prorgram showing three ways to declare predicates, in for example the "FindIndex" and "FindLastIndex" methods of Lists, but in general you can do this for any...
4
by: Arun Srinivasan | last post by:
Hi I was using a query previously, that was efficient select * from table where pred1 and pred2 and pred3; Later I was asked to introduce new ones, but they were not based on table columns but...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.