Search Results

Search found 1037 results on 42 pages for 'lambda calculus'.

Page 5/42 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Create lambda action from function expression

    - by Martin Robins
    It is relatively easy to create a lambda function that will return the value of a property from an object, even including deep properties... Func<Category, string> getCategoryName = new Func<Category, string>(c => c.Name); and this can be called as follows... string categoryName = getCategoryName(this.category); But, given only the resulting function above (or the expression originally used to create the function), can anybody provide an easy way to create the opposing action... Action<Category, string> setCategoryName = new Action<Category, string>((c, s) => c.Name = s); ...that will enable the same property value to be set as follows? setCategoryName(this.category, ""); Note that I am looking for a way to create the action programatically from the function or expression - I hope that I have shown that I already know how to create it manually. I am open to answers that work in both .net 3.5 and 4.0. Thanks.

    Read the article

  • for loop vs std::for_each with lambda

    - by Andrey
    Let's consider a template function written in C++11 which iterates over a container. Please exclude from consideration the range loop syntax because it is not yet supported by the compiler I'm working with. template <typename Container> void DoSomething(const Container& i_container) { // Option #1 for (auto it = std::begin(i_container); it != std::end(i_container); ++it) { // do something with *it } // Option #2 std::for_each(std::begin(i_container), std::end(i_container), [] (typename Container::const_reference element) { // do something with element }); } What are pros/cons of for loop vs std::for_each in terms of: a) performance? (I don't expect any difference) b) readability and maintainability? Here I see many disadvantages of for_each. It wouldn't accept a c-style array while the loop would. The declaration of the lambda formal parameter is so verbose, not possible to use auto there. It is not possible to break out of for_each. In pre- C++11 days arguments against for were a need of specifying the type for the iterator (doesn't hold any more) and an easy possibility of mistyping the loop condition (I've never done such mistake in 10 years). As a conclusion, my thoughts about for_each contradict the common opinion. What am I missing here?

    Read the article

  • Can I use a method as a lambda?

    - by NewAlexandria
    I have an interface the defines a group of conditions. it is one of several such interfaces that will live with other models. These conditions will be called by a message queue handler to determine completeness of an alert. All the alert calls will be the same, and so I seek to DRY up the enqueue calls a bit, by abstracting the the conditions into their own methods (i question if methods is the right technique). I think that by doing this I will be able to test each of these conditions. class Loan module AlertTriggers def self.included(base) base.extend LifecycleScopeEnqueues # this isn't right Loan::AlertTriggers::LifecycleScopeEnqueues.instance_method.each do |cond| class << self def self.cond ::AlertHandler.enqueue_alerts( {:trigger => Loan.new}, cond ) end end end end end module LifecycleScopeEnqueues def student_awaiting_cosigner lambda { |interval, send_limit, excluding| excluding ||= '' Loan.awaiting_cosigner. where('loans.id not in (?)', excluding.map(&:id) ). joins(:petitions). where('petitions.updated_at > ?', interval.days.ago). where('petitions.updated_at <= ?', send_limit.days.ago) } end end I've considered alternatives, where each of these methods act like a scope. Down that road, I'm not sure how to have AlertHandler be the source of interval, send_limit, and excluding, which it passes to the block/proc when calling it.

    Read the article

  • c# Lambda Expression built with LinqKit does not compile

    - by Frank Michael Kraft
    This lambda does not compile, but I do not understand why. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using LinqKit; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var barModel = new BarModel(); string id = "some"; Console.WriteLine(barModel.subFor(id).ToString()); // output: m => (True AndAlso (m.key == value(ConsoleApplication2.Bar`1+<>c__DisplayClass0[ConsoleApplication2.Model]).id)) Console.ReadKey(); var subworkitems = barModel.list.Where(barModel.subFor(id).Compile()); // Exception {"variable 'm' of type 'ConsoleApplication2.Model' referenced from scope '', but it is not defined"} Console.WriteLine(subworkitems.ToString()); Console.ReadKey(); } } class Bar<TModel> { public Bar(Expression<Func<TModel, string>> foreignKeyExpression) { _foreignKeyExpression = foreignKeyExpression; } private Expression<Func<TModel, string>> _foreignKeyExpression { get; set; } public Expression<Func<TModel, bool>> subFor(string id) { var ex = forTargetId(id); return ex; } public Expression<Func<TModel, bool>> forTargetId(String id) { var fc = _foreignKeyExpression; Expression<Func<TModel, bool>> predicate = m => true; var result = predicate.And(m => fc.Invoke(m) == id).Expand(); return result; } } class Model { public string key; public string value; } class BarModel : Bar<Model> { public List<Model> list; public BarModel() : base(m => m.key) { list = new List<Model>(); } } }

    Read the article

  • Food For Tests: 7u12 Build b05, 8 with Lambda Preview b68

    - by $utils.escapeXML($entry.author)
    This week brought along new developer preview releases of the JDK and related projects. On the JDK 7 side, the Java™ Platform, Standard Edition 7 Update 12 Developer Preview Releases have been updated to 7u12 Build b05. On the JDK 8 side, as Mike Duigou announced on the lambda-dev mailing list, A new promotion (b68) of preview binaries for OpenJDK Java 8 with lambda extensions is now available at http://jdk8.java.net/lambda/. Happy testing!

    Read the article

  • How can I use linq to build an object from 1 row of data?

    - by Hcabnettek
    Hi All, I have a quick linq question. I have a stored proc that should return one row of data. I would like to use a lambda to build an object. Here's what I'm currently doing which works, but I know I should be able to use First instead of Select except I can't seem to get the syntax correct. Can anyone straighten me out here? Thanks for any help. var location = new GeoLocationDC(); DataSet ds = db.ExecuteDataSet(dbCommand); if(ds.Tables[0].Rows.Count == 1) { var rows = ds.Tables[0].AsEnumerable(); var x = rows.Select( c => new GeoLocationDC { Latitude = Convert.ToInt32(c.Field<string>("LATITUDE")), Longitude = Convert.ToInt32(c.Field<string>("LONGITUDE")) }).ToList(); if(x.Count > 0 ) { location = x[0]; } Cheers, ~ck }

    Read the article

  • How To? Use an Expression Tree to call a Generic Method when the Type is only known at runtime.

    - by David Williams
    Please bear with me; I am very new to expression trees and lambda expressions, but trying to learn. This is something that I solved using reflection, but would like to see how to do it using expression trees. I have a generic function: private void DoSomeThing<T>( param object[] args ) { // Some work is done here. } that I need to call from else where in my class. Now, normally, this would be be simple: DoSomeThing<int>( blah ); but only if I know, at design time that I am working with an int. When I do not know the type until runtime is where I need the help. Like I said, I know how to do it via reflection, but I would like to do it via expression trees, as my (very limited) understanding is that I can do so. Any suggestions or points to sites where I can get this understanding, preferably with sample code?

    Read the article

  • How can I make Church numerals more human readable in lisp?

    - by Jason Baker
    I can define church numerals fairly easy using scheme: > (define f (lambda (x) x)) > (f f) ;0 #<procedure:f> > (f (f f)) ;1 #<procedure:f> However, this doesn't make it very easy to recognize that (f f) is 0 and (f (f f)) is 1. Is there a way that I can make these numerals more readable? What would be ideal is this: > (f f) 0 > (f (f f)) 1 The example is in scheme, but I'll take an answer in any lisp.

    Read the article

  • Help a C# developer understand: What is a monad?

    - by Charlie Flowers
    There is a lot of talk about monads these days. I have read a few articles / blog posts, but I can't go far enough with their examples to fully grasp the concept. The reason is that monads are a functional language concept, and thus the examples are in languages I haven't worked with (since I haven't used a functional language in depth). I can't grasp the syntax deeply enough to follow the articles fully ... but I can tell there's something worth understanding there. However, I know C# pretty well, including lambda expressions and other functional features. I know C# only has a subset of functional features, and so maybe monads can't be expressed in C#. However, surely it is possible to convey the concept? At least I hope so. Maybe you can present a C# example as a foundation, and then describe what a C# developer would wish he could do from there but can't because the language lacks functional programming features. This would be fantastic, because it would convey the intent and benefits of monads. So here's my question: What is the best explanation you can give of monads to a C# 3 developer? Thanks! (EDIT: By the way, I know there are at least 3 "what is a monad" questions already on SO. However, I face the same problem with them ... so this question is needed imo, because of the C#-developer focus. Thanks.)

    Read the article

  • How can I make this work with deep properties

    - by Martin Robins
    Given the following code... class Program { static void Main(string[] args) { Foo foo = new Foo { Bar = new Bar { Name = "Martin" }, Name = "Martin" }; DoLambdaStuff(foo, f => f.Name); DoLambdaStuff(foo, f => f.Bar.Name); } static void DoLambdaStuff<TObject, TValue>(TObject obj, Expression<Func<TObject, TValue>> expression) { // Set up and test "getter"... Func<TObject, TValue> getValue = expression.Compile(); TValue stuff = getValue(obj); // Set up and test "setter"... ParameterExpression objectParameterExpression = Expression.Parameter(typeof(TObject)), valueParameterExpression = Expression.Parameter(typeof(TValue)); Expression<Action<TObject, TValue>> setValueExpression = Expression.Lambda<Action<TObject, TValue>>( Expression.Block( Expression.Assign(Expression.Property(objectParameterExpression, ((MemberExpression)expression.Body).Member.Name), valueParameterExpression) ), objectParameterExpression, valueParameterExpression ); Action<TObject, TValue> setValue = setValueExpression.Compile(); setValue(obj, stuff); } } class Foo { public Bar Bar { get; set; } public string Name { get; set; } } class Bar { public string Name { get; set; } } The call to DoLambdaStuff(foo, f => f.Name) works ok because I am accessing a shallow property, however the call to DoLambdaStuff(foo, f => f.Bar.Name) fails - although the creation of the getValue function works fine, the creation of the setValueExpression fails because I am attempting to access a deep property of the object. Can anybody please help me to modify this so that I can create the setValueExpression for deep properties as well as shallow? Thanks.

    Read the article

  • Ruby Design Problem for SQL Bulk Inserter

    - by crunchyt
    This is a Ruby design problem. How can I make a reusable flat file parser that can perform different data scrubbing operations per call, return the emitted results from each scrubbing operation to the caller and perform bulk SQL insertions? Now, before anyone gets narky/concerned, I have written this code already in a very unDRY fashion. Which is why I am asking any Ruby rockstars our there for some assitance. Basically, everytime I want to perform this logic, I create two nested loops, with custom processing in between, buffer each processed line to an array, and output to the DB as a bulk insert when the buffer size limit is reached. Although I have written lots of helpers, the main pattern is being copy pasted everytime. Not very DRY! Here is a Ruby/Pseudo code example of what I am repeating. lines_from_file.each do |line| line.match(/some regex/).each do |sub_str| # Process substring into useful format # EG1: Simple gsub() call # EG2: Custom function call to do complex scrubbing # and matching, emitting results to array # EG3: Loop to match opening/closing/nested brackets # or other delimiters and emit results to array end # Add processed lines to a buffer as SQL insert statement @buffer << PREPARED INSERT STATEMENT # Flush buffer when "buffer size limit reached" or "end of file" if sql_buffer_full || last_line_reached @dbc.insert(SQL INSERTS FROM BUFFER) @buffer = nil end end I am familiar with Proc/Lambda functions. However, because I want to pass two separate procs to the one function, I am not sure how to proceed. I have some idea about how to solve this, but I would really like to see what the real Rubyists suggest? Over to you. Thanks in advance :D

    Read the article

  • Properly handling possible System.NullReferenceException in lambda expressions

    - by Travis Johnson
    Here's the query in question return _projectDetail.ExpenditureDetails .Where(detail => detail.ProgramFund == _programFund && detail.Expenditure.User == _creditCardHolder) .Sum(detail => detail.ExpenditureAmounts.FirstOrDefault( amount => amount.isCurrent && !amount.requiresAudit) .CommittedMonthlyRecord.ProjectedEac); Table Structure ProjectDetails (1 to Many) ExpenditureDetails ExpenditureDetails (1 to Many) ExpenditureAmounts ExpenditureAmounts (1 to 1) CommittedMonthlyRecords ProjectedEac is a decimal field on the CommittedMonthlyRecords. The problem I discovered in a Unit test (albeit an unlikely event), that the following line could be null: detail.ExpenditureAmounts.FirstOrDefault( amount => amount.isCurrent && !amount.requiresAudit) My original query was a nested loop, in where I would be making multiple trips to the database, something I don't want to repeat. I've looked in to what seemed like some similar questions here, but the solution didn't seem to fit. Any ideas?

    Read the article

  • How does C# lambda work?

    - by Alex
    I'm trying to implement method Find that searches the database. I want it to be like that: var user = User.Find(a => a.LastName == "Brown"); Like it's done in List class. But when I go to List's source code (thanks, Reflector), I see this: public T Find(Predicate<T> match) { if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < this._size; i++) { if (match(this._items[i])) { return this._items[i]; } } return default(T); } How can I implement this thing? I need to get those parameters to make the search.

    Read the article

  • List<T>.SelectMany(), Linq and lambda help

    - by jim
    Hi there I have a class. public class MedicalRequest { private int id private IList<MedicalDays> Days private string MedicalUser ... } and another public class MedicalDays { private int id; private DateTime? day private MedicalRequest request ... } I'm using nhibernate to return a list of all the MedicalDays within a time span. I'd like to do something like this to the resulting list //nhibernate query IList<MedicalDays> days = daysDao.FindAll(searchCritCollection); //select a list of days from resulting list IEnumerable<MedicalDays> queriedList = days.SelectMany(i => i.MedicalRequest.MedicalUser == employee); Linq tells me that the type cannot be inferred by the usage. I'd like to know what I'm doing wrong, and if there is a preferred way of doing something like this. Thanks for your time.

    Read the article

  • Weird bug with C++ lambda expressions in VS2010

    - by Andrei Tita
    In a couple of my projects, the following code: class SmallClass { public: int x1, y1; void TestFunc() { auto BadLambda = [&]() { int g = x1 + 1; //ok int h = y1 + 1; //c2296 int l = static_cast<int>(y1); //c2440 }; int y1_copy = y1; //it works if you create a local copy auto GoodLambda = [&]() { int h = y1_copy + 1; //ok int l = this->y1 + 1; //ok }; } }; generates error C2296: '+' : illegal, left operand has type 'double (__cdecl *)(double)' or alternatively error C2440: 'static_cast' : cannot convert from 'double (__cdecl *)(double)' to 'int' You get the picture. It also happens if catching by value. The error seems to be tied to the member name "y1". It happened in different classes, different projects and with (seemingly) any type for y1; for example, this code: [...] MyClass y1; void TestFunc() { auto BadLambda = [&]()->void { int l = static_cast<int>(y1); //c2440 }; } generates both these errors: error C2440: 'static_cast' : cannot convert from 'MyClass' to 'int' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called error C2440: 'static_cast' : cannot convert from 'double (__cdecl *)(double)' to 'int' There is no context in which this conversion is possible It didn't, however, happen in a completely new project. I thought maybe it was related to Lua (the projects where I managed to reproduce this bug both used Lua), but I did not manage to reproduce it in a new project linking Lua. It doesn't seem to be a known bug, and I'm at a loss. Any ideas as to why this happens? (I don't need a workaround; there are a few in the code already). Using Visual Studio 2010 Express version 10.0.40219.1 Sp1Rel.

    Read the article

  • Getting error in MVC Proj while writing Lambda Expression

    - by Shrewd Demon
    hi, i am creating a sample movie (MVC) application. I was getting fine with Viewing and Creating a new record, but when i wrote the code to get the details of a particular record i met with the following error: Unable to cast objec`t of type 'System.Data.Objects.ObjectQuery`1[MovieApp.Models.Movie]' to type 'MovieApp.Model`s.Movie'. here is the code i wrote for getting the details public ActionResult Details(int id) { var moviedetail = (Movie)_entities.MovieSet.Where(mvid => mvid.Id == id); return View(moviedetail); } can any body tell me whats going wrong and where ?? thank you.

    Read the article

  • Render Html from a lambda in MVC

    - by Thad
    I have the following code to generate a list and will allow developers to customize the output if needed. <% Html.List<MyList>(item => item.Property).Value(item => return "<div>" + item.Property + "<br/>" + item.AnotherProperty + "</div>").Render() %> This is not ideal, how can I allow the developers to add the html similar to other controls. <% Html.List<MyList>(item => item.Property).Value(item => %> <div><%=item.Property%><br/><%=item.AnotherProperty%></div><%).Render() %> This way is much cleaner and standard with the rest of mvc.

    Read the article

  • Assign to a slice of a Python list from a lambda

    - by Bushman
    I know that there are certain "special" methods of various objects that represent operations that would normally be performed with operators (i.e. int.__add__ for +, object.__eq__ for ==, etc.), and that one of them is list.__setitem, which can assign a value to a list element. However, I need a function that can assign a list into a slice of another list. Basically, I'm looking for the expression equivalent of some_list[2:4] = [2, 3].

    Read the article

  • lambda expression for a query on two tables that returns records from one table

    - by peetee
    I have two tables TableA (articles) int id int Type string name and TableB (compatibles) int linked_ID int tableA_ID TableA records: id=1, Type=0, name="ArticleA" id=2, Type=1, name="ArticleB" id=3, Type=2, name="ArticleC" id=4, Type=1, name="ArticleD" TableB records: linked_ID= 1, tableA_ID=2 linked_ID= 1, tableA_ID=3 linked_ID= 1, tableA_ID=4 TableB has a list of arcicels that are compatible to a certain article. I am quite new to queries (didn't need them in my projects yet). But as C# and WPF allow some pretty cool automation with Binding I would like to add a binding that returns the following: Give me all articles that are of Type 1 and compatible to my selected article (id=1). The simple part of it works well (articles has a list of all articles): private ObservableCollection<Article> _articles = new ObservableCollection<Article>(); [fill it with the available articles] and then: comboBoxArticles.ItemsSource = _articles.AsBindable().Where( c => c.Typ == 0 ); How can I extend the Where clause to query another table? Thanks a lot in advance.

    Read the article

  • Need help with this basic Contains<>() extension method and Lambda expressions

    - by Polaris878
    Hi, Say I have the following class: class Foo { // ctor etc here public string Bar { get; } } Now, I have a LinkedList of Foos declared like so: LinkedList<Foo> How would I write a basic Contains<() for this? I want to be able to do this: Foo foo = new Foo(someString); LinkedList<Foo> list = new LinkedList<foo>(); // Populate list with Foos bool contains = list.Contains<Foo>(foo, (x => foo.Bar == x.Bar)); Am I trying to do this correctly? Thanks

    Read the article

  • Convert C# Lambda to vb.net

    - by Joven
    Need Help in converting this to VB.NET public void GetCustomers(Action<IEnumerable<Customer>> onSuccess, Action<Exception> onFail) { Manager.Customers.ExecuteAsync(op => { if (op.CompletedSuccessfully) { if (onSuccess != null) onSuccess(op.Results); } else { if (onFail != null) { op.MarkErrorAsHandled(); onFail(op.Error); } } } ); }

    Read the article

  • Converting ObsevableCollection foreach to lambda.

    - by Jitendra Jadav
    Hello Guys, I am working some ObservableCollection converting to lembda it will give me error this is my actual code . foreach (var item in Query) { userDetail.Add(new UserDatail(item.ID,item.Name, item.Address, item.City, item.Pin, item.Phone)); } and I am try to add as lembda Query.ToList().ForEach(x => userDetail.Add(x.ID,x.Name,x.Address,x.City,x.Pin,x.Phone)); This will give me error. Thanks..

    Read the article

  • How to pass a Lambda Expression as method parameter with EF

    - by Registered User
    How do I pass an EF expression as a method argument? To illustrate my question I have created a pseudo code example: The first example is my method today. The example utilizes EF and a Fancy Retry Logic. What I need to do is to encapsulate the Fancy Retry Logic so that it becomes more generic and does not duplicate. In the second example is how I want it to be, with a helper method that accepts the EF expression as an argument. This would be a trivial thing to do with SQL, but I want to do it with EF so that I can benefit from the strongly typed objects. First Example: public static User GetUser(String userEmail) { using (MyEntities dataModel = new MyEntities ()) { var query = FancyRetryLogic(() => { (dataModel.Users.FirstOrDefault<User>(x => x.UserEmail == userEmail))); }); return query; } } Second Example: T RetryHelper<T>(Expression<Func<T, TValue>> expression) { using (MyEntities dataModel = new (MyEntities ()) { var query = FancyRetryLogic(() => { return dataModel.expression }); } } public User GetUser(String userEmail) { return RetryHelper<User>(<User>.FirstOrDefault<User>(x => x.UserEmail == userEmail)) }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >