Search Results

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

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

  • Restrictons of Python compared to Ruby: lambda's

    - by Shyam
    Hi, I was going over some pages from WikiVS, that I quote from: because lambdas in Python are restricted to expressions and cannot contain statements I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language. Thank you for your answers, comments and feedback!

    Read the article

  • Nested for_each with lambda not possible?

    - by Ela782
    The following code does not compile in VS2012, it gives error C2064: term does not evaluate to a function taking 1 arguments on the line of the second for_each (line 4 below). vector<string> v1; for_each(begin(v1), end(v1), [](string s1) { vector<string> v2; for_each(begin(v2), end(v2), [](string s2) { cout << "..."; }); }); I found some related stuff like http://connect.microsoft.com/VisualStudio/feedback/details/560907/capturing-variables-in-nested-lambdas which shows a bug (they are doing something different) but on the other hand that shows that what I print above should be possible. What's wrong with the above code?

    Read the article

  • Extract information from a Func<bool, T> or alike lambda

    - by Syska
    I''m trying to build a generic cache layer. ICacheRepository Say I have the following: public class Person { public int PersonId { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public DateTime Added { get; set; } } And I have something like this: list.Where(x => x.Firstname == "Syska"); Here I want to extract the above information, to see if the query supplied the "PersonId" which it did not, so I dont want to cache it. But lets say I run a query like this: list.Where(x => x.PersonId == 10); Since PersonId is my key ... I want to cache it. with the key like "Person_10" and I later can fetch it from the cache. I know its possible to extract the information with Expression<Func<>> but there seems to be a big overhead of doing this (when running compile and extract the Constant values etc. and a bunch of cache to be sure to parse right) Are there a framework for this? Or some smart/golden way of doing this ?

    Read the article

  • Lambda expression will not compile

    - by John Soer
    I am very confused. I have this lamba expression: tvPatientPrecriptionsEntities.Sort((p1, p2) => p1.MedicationStartDate .Value .CompareTo(p2.MedicationStartDate.Value)); Visual Studio will not compile it and complains about syntax. I converted the lamba expression to an anonymous delegate as so: tvPatientPrecriptionsEntities.Sort( delegate(PatientPrecriptionsEntity p1, PatientPrecriptionsEntity p2) { return p1.MedicationStartDate .Value .CompareTo(p2.MedicationStartDate.Value); }); and it works fine. The project uses .NET 3.5 and I have a reference to System.Linq.

    Read the article

  • How to pass data to a C++0x lambda function that will run in a different thread?

    - by Dimitri C.
    In our company we've written a library function to call a function asynchronously in a separate thread. It works using a combination of inheritance and template magic. The client code looks as follows: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, &DemoThread::SomeFunction, stringToPassByValue); Since the introduction of lambda functions I'd like to use it in combination with lambda functions. I'd like to write the following client code: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, [=]() { const std::string someCopy = stringToPassByValue; }); Now, with the Visual C++ 2010 this code doesn't work. What happens is that the stringToPassByValue is not copied. Instead the "capture by value" feature passes the data by reference. The result is that if the function is executed after stringToPassByValue has gone out of scope, the application crashes as its destructor is called already. So I wonder: is it possible to pass data to a lambda function as a copy? Note: One possible solution would be to modify our framework to pass the data in the lambda parameter declaration list, as follows: DemoThread thread; std::string stringToPassByValue = "The string to pass by value"; AsyncCall(thread, [=](const std::string stringPassedByValue) { const std::string someCopy = stringPassedByValue; } , stringToPassByValue); However, this solution is so verbose that our original function pointer solution is both shorter and easier to read. Update: The full implementation of AsyncCall is too big to post here. In short, what happens is that the AsyncCall template function instantiates a template class holding the lambda function. This class is derived from a base class that contains a virtual Execute() function, and upon an AsyncCall() call, the function call class is put on a call queue. A different thread then executes the queued calls by calling the virtual Execute() function, which is polymorphically dispatched to the template class which then executes the lambda function.

    Read the article

  • C# LINQ Where Predicate Type Arguments

    - by blu
    I have an XElement with values for mock data. I have an expression to query the xml: Expression<Func<XElement, bool>> simpleXmlFunction = b => int.Parse(b.Element("FooId").Value) == 12; used in: var simpleXml = xml.Elements("Foo").Where(simpleXmlFunction).First(); The design time error is: The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly' The delegate supplied to Where should take in an XElement and return a bool, marking if the item matches the query, I am not sure how to add anything more to the delegate or the where clause to mark the type. Also, the parallel method for the real function against the Entity Framework does not have this issue. What is not correct with the LINQ-to-XML version?

    Read the article

  • LinqToXML why does my object go out of scope? Also should I be doing a group by?

    - by Kettenbach
    Hello All, I have an IEnumerable<someClass>. I need to transform it into XML. There is a property called 'ZoneId'. I need to write some XML based on this property, then I need some decendent elements that provide data relevant to the ZoneId. I know I need some type of grouping. Here's what I have attempted thus far without much success. **inventory is an IEnumerable<someClass>. So I query inventory for unique zones. This works ok. var zones = inventory.Select(c => new { ZoneID = c.ZoneId , ZoneName = c.ZoneName , Direction = c.Direction }).Distinct(); No I want to create xml based on zones and place. ***place is a property of 'someClass'. var xml = new XElement("MSG_StationInventoryList" , new XElement("StationInventory" , zones.Select(station => new XElement("station-id", station.ZoneID) , new XElement("station-name", station.ZoneName)))); This does not compile as "station" is out of scope when I try to add the "station-name" element. However is I remove the paren after 'ZoneId', station is in scope and I retreive the station-name. Only problem is the element is then a decendant of 'station-id'. This is not the desired output. They should be siblings. What am I doing wrong? Lastly after the "station-name" element, I will need another complex type which is a collection. Call it "places'. It will have child elements called "place". its data will come from the IEnumerable and I will only want "places" that have the "ZoneId" for the current zone. Can anyone point me in the right direction? Is it a mistake select distinct zones from the original IEnumerable? This object has all the data I need within it. I just need to make it heirarchical. Thanks for any pointers all. Cheers, Chris in San Diego

    Read the article

  • How can i filter a list of objects using lamda expression?

    - by Colour Blend
    I know i shouldn't have id's with the same value. This is just fictitious, so overlook that. I have: List<Car> carList = new List<Car>(); carList.Add(new Car() { id = 1, name = "Honda" }); carList.Add(new Car() { id = 2, name = "Toyota" }); carList.Add(new Car() { id = 1, name = "Nissan" }); I want to use Lamda Expression to retreive all cars that have an id of 1. Anticipated Result: -- Id: 1, Name: Honda -- Id: 1, Name: Nissan The problem is more filtering an object list based on a foriegn key. Please help me.

    Read the article

  • Calculus? Need help solving for a time-dependent variable given some other variables.

    - by user451527
    Long story short, I'm making a platform game. I'm not old enough to have taken Calculus yet, so I know not of derivatives or integrals, but I know of them. The desired behavior is for my character to automagically jump when there is a block to either side of him that is above the one he's standing on; for instance, stairs. This way the player can just hold left / right to climb stairs, instead of having to spam the jump key too. The issue is with the way I've implemented jumping; I've decided to go mario-style, and allow the player to hold 'jump' longer to jump higher. To do so, I have a 'jump' variable which is added to the player's Y velocity. The jump variable increases to a set value when the 'jump' key is pressed, and decreases very quickly once the 'jump' key is released, but decreases less quickly so long as you hold the 'jump' key down, thus providing continuous acceleration up as long as you hold 'jump.' This also makes for a nice, flowing jump, rather than a visually jarring, abrupt acceleration. So, in order to account for variable stair height, I want to be able to calculate exactly what value the 'jump' variable should get in order to jump exactly to the height of the stair; preferably no more, no less, though slightly more is permissible. This way the character can jump up steep or shallow flights of stairs without it looking weird or being slow. There are essentially 5 variables in play: h -the height the character needs to jump to reach the stair top<br> j -the jump acceleration variable<br> v -the vertical velocity of the character<br> p -the vertical position of the character<br> d -initial vertical position of the player minus final position<br> Each timestep:<br> j -= 1.5; //the jump variable's deceleration<br> v -= j; //the jump value's influence on vertical speed<br> v *= 0.95; //friction on the vertical speed<br> v += 1; //gravity<br> p += v; //add the vertical speed to the vertical position<br> v-initial is known to be zero<br> v-final is known to be zero<br> p-initial is known<br> p-final is known<br> d is known to be p-initial minus p-final<br> j-final is known to be zero<br> j-initial is unknown<br> Given all of these facts, how can I make an equation that will solve for j? tl;dr How do I Calculus? Much thanks to anyone who's made it this far and decides to plow through this problem.

    Read the article

  • boost::function & boost::lambda again

    - by John Dibling
    Follow-up to post: http://stackoverflow.com/questions/2978096/using-width-precision-specifiers-with-boostformat I'm trying to use boost::function to create a function that uses lambdas to format a string with boost::format. Ultimately what I'm trying to achieve is using width & precision specifiers for strings with format. boost::format does not support the use of the * width & precision specifiers, as indicated in the docs: Width or precision set to asterisk (*) are used by printf to read this field from an argument. e.g. printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec); This class does not support this mechanism for now. so such precision or width fields are quietly ignored by the parsing. so I'm trying to find other ways to accomplish the same goal. Here is what I have so far, which isn't working: #include <string> #include <boost\function.hpp> #include <boost\lambda\lambda.hpp> #include <iostream> #include <boost\format.hpp> #include <iomanip> #include <boost\bind.hpp> int main() { using namespace boost::lambda; using namespace std; boost::function<std::string(int, std::string)> f = (boost::format("%s") % boost::io::group(setw(_1*2), setprecision(_2*2), _3)).str(); std::string s = (boost::format("%s") % f(15, "Hello")).str(); return 0; } This generates many compiler errors: 1>------ Build started: Project: hacks, Configuration: Debug x64 ------ 1>Compiling... 1>main.cpp 1>.\main.cpp(15) : error C2872: '_1' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(69) : boost::lambda::placeholder1_type &boost::lambda::`anonymous-namespace'::_1' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(43) : boost::arg<I> `anonymous-namespace'::_1' 1> with 1> [ 1> I=1 1> ] 1>.\main.cpp(15) : error C2664: 'std::setw' : cannot convert parameter 1 from 'boost::lambda::placeholder1_type' to 'std::streamsize' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1>.\main.cpp(15) : error C2872: '_2' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(70) : boost::lambda::placeholder2_type &boost::lambda::`anonymous-namespace'::_2' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(44) : boost::arg<I> `anonymous-namespace'::_2' 1> with 1> [ 1> I=2 1> ] 1>.\main.cpp(15) : error C2664: 'std::setprecision' : cannot convert parameter 1 from 'boost::lambda::placeholder2_type' to 'std::streamsize' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1>.\main.cpp(15) : error C2872: '_3' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(71) : boost::lambda::placeholder3_type &boost::lambda::`anonymous-namespace'::_3' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(45) : boost::arg<I> `anonymous-namespace'::_3' 1> with 1> [ 1> I=3 1> ] 1>.\main.cpp(15) : error C2660: 'boost::io::group' : function does not take 3 arguments 1>.\main.cpp(15) : error C2228: left of '.str' must have class/struct/union 1>Build log was saved at "file://c:\Users\john\Documents\Visual Studio 2005\Projects\hacks\x64\Debug\BuildLog.htm" 1>hacks - 7 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== My fundamental understanding of boost's lambdas and functions is probably lacking. How can I get this to work?

    Read the article

  • How do I tell if an action is a lambda expression?

    - by Keith
    I am using the EventAgregator pattern to subscribe and publish events. If a user subscribes to the event using a lambda expression, they must use a strong reference, not a weak reference, otherwise the expression can be garbage collected before the publish will execute. I wanted to add a simple check in the DelegateReference so that if a programmer passes in a lambda expression and is using a weak reference, that I throw an argument exception. This is to help "police" the code. Example: eventAggregator.GetEvent<RuleScheduler.JobExecutedEvent>().Subscribe ( e => resetEvent.Set(), ThreadOption.PublisherThread, false, // filter event, only interested in the job that this object started e => e.Value1.JobDetail.Name == jobName ); public DelegateReference(Delegate @delegate, bool keepReferenceAlive) { if (@delegate == null) throw new ArgumentNullException("delegate"); if (keepReferenceAlive) { this._delegate = @delegate; } else { //TODO: throw exception if target is a lambda expression _weakReference = new WeakReference(@delegate.Target); _method = @delegate.Method; _delegateType = @delegate.GetType(); } } any ideas? I thought I could check for @delegate.Method.IsStatic but I don't believe that works... (is every lambda expression a static?)

    Read the article

  • C++/boost generator module, feedback/critic please

    - by aaa
    hello. I wrote this generator, and I think to submit to boost people. Can you give me some feedback about it it basically allows to collapse multidimensional loops to flat multi-index queue. Loop can be boost lambda expressions. Main reason for doing this is to make parallel loops easier and separate algorithm from controlling structure (my fieldwork is computational chemistry where deep loops are common) 1 #ifndef _GENERATOR_HPP_ 2 #define _GENERATOR_HPP_ 3 4 #include <boost/array.hpp> 5 #include <boost/lambda/lambda.hpp> 6 #include <boost/noncopyable.hpp> 7 8 #include <boost/mpl/bool.hpp> 9 #include <boost/mpl/int.hpp> 10 #include <boost/mpl/for_each.hpp> 11 #include <boost/mpl/range_c.hpp> 12 #include <boost/mpl/vector.hpp> 13 #include <boost/mpl/transform.hpp> 14 #include <boost/mpl/erase.hpp> 15 16 #include <boost/fusion/include/vector.hpp> 17 #include <boost/fusion/include/for_each.hpp> 18 #include <boost/fusion/include/at_c.hpp> 19 #include <boost/fusion/mpl.hpp> 20 #include <boost/fusion/include/as_vector.hpp> 21 22 #include <memory> 23 24 /** 25 for loop generator which can use lambda expressions. 26 27 For example: 28 @code 29 using namespace generator; 30 using namespace boost::lambda; 31 make_for(N, N, range(bind(std::max<int>, _1, _2), N), range(_2, _3+1)); 32 // equivalent to pseudocode 33 // for l=0,N: for k=0,N: for j=max(l,k),N: for i=k,j 34 @endcode 35 36 If range is given as upper bound only, 37 lower bound is assumed to be default constructed 38 Lambda placeholders may only reference first three indices. 39 */ 40 41 namespace generator { 42 namespace detail { 43 44 using boost::lambda::constant_type; 45 using boost::lambda::constant; 46 47 /// lambda expression identity 48 template<class E, class enable = void> 49 struct lambda { 50 typedef E type; 51 }; 52 53 /// transform/construct constant lambda expression from non-lambda 54 template<class E> 55 struct lambda<E, typename boost::disable_if< 56 boost::lambda::is_lambda_functor<E> >::type> 57 { 58 struct constant : boost::lambda::constant_type<E>::type { 59 typedef typename boost::lambda::constant_type<E>::type base_type; 60 constant() : base_type(boost::lambda::constant(E())) {} 61 constant(const E &e) : base_type(boost::lambda::constant(e)) {} 62 }; 63 typedef constant type; 64 }; 65 66 /// range functor 67 template<class L, class U> 68 struct range_ { 69 typedef boost::array<int,4> index_type; 70 range_(U upper) : bounds_(typename lambda<L>::type(), upper) {} 71 range_(L lower, U upper) : bounds_(lower, upper) {} 72 73 template< typename T, size_t N> 74 T lower(const boost::array<T,N> &index) { 75 return bound<0>(index); 76 } 77 78 template< typename T, size_t N> 79 T upper(const boost::array<T,N> &index) { 80 return bound<1>(index); 81 } 82 83 private: 84 template<bool b, typename T> 85 T bound(const boost::array<T,1> &index) { 86 return (boost::fusion::at_c<b>(bounds_))(index[0]); 87 } 88 89 template<bool b, typename T> 90 T bound(const boost::array<T,2> &index) { 91 return (boost::fusion::at_c<b>(bounds_))(index[0], index[1]); 92 } 93 94 template<bool b, typename T, size_t N> 95 T bound(const boost::array<T,N> &index) { 96 using boost::fusion::at_c; 97 return (at_c<b>(bounds_))(index[0], index[1], index[2]); 98 } 99 100 boost::fusion::vector<typename lambda<L>::type, 101 typename lambda<U>::type> bounds_; 102 }; 103 104 template<typename T, size_t N> 105 struct for_base { 106 typedef boost::array<T,N> value_type; 107 virtual ~for_base() {} 108 virtual value_type next() = 0; 109 }; 110 111 /// N-index generator 112 template<typename T, size_t N, class R, class I> 113 struct for_ : for_base<T,N> { 114 typedef typename for_base<T,N>::value_type value_type; 115 typedef R range_tuple; 116 for_(const range_tuple &r) : r_(r), state_(true) { 117 boost::fusion::for_each(r_, initialize(index)); 118 } 119 /// @return new generator 120 for_* new_() { return new for_(r_); } 121 /// @return next index value and increment 122 value_type next() { 123 value_type next; 124 using namespace boost::lambda; 125 typename value_type::iterator n = next.begin(); 126 typename value_type::iterator i = index.begin(); 127 boost::mpl::for_each<I>(*(var(n))++ = var(i)[_1]); 128 129 state_ = advance<N>(r_, index); 130 return next; 131 } 132 /// @return false if out of bounds, true otherwise 133 operator bool() { return state_; } 134 135 private: 136 /// initialize indices 137 struct initialize { 138 value_type &index_; 139 mutable size_t i_; 140 initialize(value_type &index) : index_(index), i_(0) {} 141 template<class R_> void operator()(R_& r) const { 142 index_[i_++] = r.lower(index_); 143 } 144 }; 145 146 /// advance index[0:M) 147 template<size_t M> 148 struct advance { 149 /// stop recursion 150 struct stop { 151 stop(R r, value_type &index) {} 152 }; 153 /// advance index 154 /// @param r range tuple 155 /// @param index index array 156 advance(R &r, value_type &index) : index_(index), i_(0) { 157 namespace fusion = boost::fusion; 158 index[M-1] += 1; // increment index 159 fusion::for_each(r, *this); // update indices 160 state_ = index[M-1] >= fusion::at_c<M-1>(r).upper(index); 161 if (state_) { // out of bounds 162 typename boost::mpl::if_c<(M > 1), 163 advance<M-1>, stop>::type(r, index); 164 } 165 } 166 /// apply lower bound of range to index 167 template<typename R_> void operator()(R_& r) const { 168 if (i_ >= M) index_[i_] = r.lower(index_); 169 ++i_; 170 } 171 /// @return false if out of bounds, true otherwise 172 operator bool() { return state_; } 173 private: 174 value_type &index_; ///< index array reference 175 mutable size_t i_; ///< running index 176 bool state_; ///< out of bounds state 177 }; 178 179 value_type index; 180 range_tuple r_; 181 bool state_; 182 }; 183 184 185 /// polymorphic generator template base 186 template<typename T,size_t N> 187 struct For : boost::noncopyable { 188 typedef boost::array<T,N> value_type; 189 /// @return next index value and increment 190 value_type next() { return for_->next(); } 191 /// @return false if out of bounds, true otherwise 192 operator bool() const { return for_; } 193 protected: 194 /// reset smart pointer 195 void reset(for_base<T,N> *f) { for_.reset(f); } 196 std::auto_ptr<for_base<T,N> > for_; 197 }; 198 199 /// range [T,R) type 200 template<typename T, typename R> 201 struct range_type { 202 typedef range_<T,R> type; 203 }; 204 205 /// range identity specialization 206 template<typename T, class L, class U> 207 struct range_type<T, range_<L,U> > { 208 typedef range_<L,U> type; 209 }; 210 211 namespace fusion = boost::fusion; 212 namespace mpl = boost::mpl; 213 214 template<typename T, size_t N, class R1, class R2, class R3, class R4> 215 struct range_tuple { 216 // full range vector 217 typedef typename mpl::vector<R1,R2,R3,R4> v; 218 typedef typename mpl::end<v>::type end; 219 typedef typename mpl::advance_c<typename mpl::begin<v>::type, N>::type pos; 220 // [0:N) range vector 221 typedef typename mpl::erase<v, pos, end>::type t; 222 // transform into proper range fusion::vector 223 typedef typename fusion::result_of::as_vector< 224 typename mpl::transform<t,range_type<T, mpl::_1> >::type 225 >::type type; 226 }; 227 228 229 template<typename T, size_t N, 230 class R1, class R2, class R3, class R4, 231 class O> 232 struct for_type { 233 typedef typename range_tuple<T,N,R1,R2,R3,R4>::type range_tuple; 234 typedef for_<T, N, range_tuple, O> type; 235 }; 236 237 } // namespace detail 238 239 240 /// default index order, [0:N) 241 template<size_t N> 242 struct order { 243 typedef boost::mpl::range_c<size_t,0, N> type; 244 }; 245 246 /// N-loop generator, 0 < N <= 5 247 /// @tparam T index type 248 /// @tparam N number of indices/loops 249 /// @tparam R1,... range types 250 /// @tparam O index order 251 template<typename T, size_t N, 252 class R1, class R2 = void, class R3 = void, class R4 = void, 253 class O = typename order<N>::type> 254 struct for_ : detail::for_type<T, N, R1, R2, R3, R4, O>::type { 255 typedef typename detail::for_type<T, N, R1, R2, R3, R4, O>::type base_type; 256 typedef typename base_type::range_tuple range_tuple; 257 for_(const range_tuple &range) : base_type(range) {} 258 }; 259 260 /// loop range [L:U) 261 /// @tparam L lower bound type 262 /// @tparam U upper bound type 263 /// @return range 264 template<class L, class U> 265 detail::range_<L,U> range(L lower, U upper) { 266 return detail::range_<L,U>(lower, upper); 267 } 268 269 /// make 4-loop generator with specified index ordering 270 template<typename T, class R1, class R2, class R3, class R4, class O> 271 for_<T, 4, R1, R2, R3, R4, O> 272 make_for(R1 r1, R2 r2, R3 r3, R4 r4, const O&) { 273 typedef for_<T, 4, R1, R2, R3, R4, O> F; 274 return F(F::range_tuple(r1, r2, r3, r4)); 275 } 276 277 /// polymorphic generator template forward declaration 278 template<typename T,size_t N> 279 struct For; 280 281 /// polymorphic 4-loop generator 282 template<typename T> 283 struct For<T,4> : detail::For<T,4> { 284 /// generator with default index ordering 285 template<class R1, class R2, class R3, class R4> 286 For(R1 r1, R2 r2, R3 r3, R4 r4) { 287 this->reset(make_for<T>(r1, r2, r3, r4).new_()); 288 } 289 /// generator with specified index ordering 290 template<class R1, class R2, class R3, class R4, class O> 291 For(R1 r1, R2 r2, R3 r3, R4 r4, O o) { 292 this->reset(make_for<T>(r1, r2, r3, r4, o).new_()); 293 } 294 }; 295 296 } 297 298 299 #endif /* _GENERATOR_HPP_ */

    Read the article

  • lambda vs. operator.attrGetter('xxx') as sort key in Python

    - by Paul McGuire
    I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions. If you were to change seq.sort(lambda x,y: cmp(x.xxx, y.xxx)), which is preferable: seq.sort(key=operator.attrgetter('xxx')) or: seq.sort(key=lambda a:a.xxx) I would also be interested in comments on the merits of making changes to existing code that works.

    Read the article

  • lambda vs. operator.attrgetter('xxx') as sort key function in Python

    - by Paul McGuire
    I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions. If you were to change seq.sort(lambda x,y: cmp(x.xxx, y.xxx)), which is preferable: seq.sort(key=operator.attrgetter('xxx')) or: seq.sort(key=lambda a:a.xxx) I would also be interested in comments on the merits of making changes to existing code that works.

    Read the article

  • RadioButtons and Lambda Expressions

    - by MightyZot
    Radio buttons operate in groups. They are used to present mutually exclusive lists of options. Since I started programming in Windows 20 years ago, I have always been frustrated about how they are implemented. To make them operate as a group, you put your radio buttons in a group box. Conversely, to group radio buttons in HTML, you simply give them all the same name. Radio buttons with the same name or ID in HTML operate as one mutually exclusive group of options. In C#, all your radio buttons must have unique names and you use group boxes to group them. I’m in the process of converting some old code to C# and I’m tasked with creating a user control with groups of radio buttons on it. I started out writing the traditional switch…case statements to check the appropriate radio button based upon value, loops to uncheck them all, etc. Then it occurred to me that I could stick the radio buttons in a Dictionary or List and use Lambda expressions to make my code a lot more maintainable. So, here is what I ended up with: Here is a dictionary that contains my list of radio buttons and their values. I used their values as the keys, so that I can select them by value. Now, instead of using loops and switch…case statements to control the radio buttons, I use the lambda syntax and extension methods. Selecting a Radio Button by Value This code is inside of a property accessor, so “value” represents the value passed into the property accessor. The “First” extension method uses the delegate represented by the lambda expression to select the radio button (actually KeyValuePair) that represents the passed in value. Finally, the resulting checkbox is checked. Since the radio buttons are in the same group, they function as a group, the appropriate radio button is selected while the others are unselected. Reading the Value This is the get accessor for the property that returns the value of the checked radio button. Now, if you’re using binding, this code is likely not necessary; however, I didn’t want to use binding in this case, so I think this is a good alternative to the traditional loops and switch…case statements.

    Read the article

  • What would you like to correct and/or improve in this java implementation of Chain Of Responsibility

    - by Maciek Kreft
    package design.pattern.behavioral; import design.pattern.behavioral.ChainOfResponsibility.*; public class ChainOfResponsibility { public static class Chain { private Request[] requests = null; private Handler[] handlers = null; public Chain(Handler[] handlers, Request[] requests){ this.handlers = handlers; this.requests = requests; } public void start() { for(Request r : requests) for (Handler h : handlers) if(h.handle(r)) break; } } public static class Request { private int value; public Request setValue(int value){ this.value = value; return this; } public int getValue() { return value; } } public static class Handler<T1> { private Lambda<T1> lambda = null; private Lambda<T1> command = null; public Handler(Lambda<T1> condition, Lambda<T1> command) { this.lambda = condition; this.command = command; } public boolean handle(T1 request) { if (lambda.lambda(request)) command.lambda(request); return lambda.lambda(request); } } public static abstract class Lambda<T1>{ public abstract Boolean lambda(T1 request); } } class TestChainOfResponsibility { public static void main(String[] args) { new TestChainOfResponsibility().test(); } private void test() { new Chain(new Handler[]{ // chain of responsibility new Handler<Request>( new Lambda<Request>(){ // command public Boolean lambda(Request condition) { return condition.getValue() >= 600; } }, new Lambda<Request>(){ public Boolean lambda(Request command) { System.out.println("You are rich: " + command.getValue() + " (id: " + command.hashCode() + ")"); return true; } } ), new Handler<Request>( new Lambda<Request>(){ public Boolean lambda(Request condition) { return condition.getValue() >= 100; } }, new Lambda<Request>(){ public Boolean lambda(Request command) { System.out.println("You are poor: " + command.getValue() + " (id: " + command.hashCode() + ")"); return true; } } ), }, new Request[]{ new Request().setValue(600), // chaining method new Request().setValue(100), } ).start(); } }

    Read the article

  • How to properly translate the "var" result of a lambda expression to a concrete type?

    - by CrimsonX
    So I'm trying to learn more about lambda expressions. I read this question on stackoverflow, concurred with the chosen answer, and have attempted to implement the algorithm using a console app in C# using a simple LINQ expression. My question is: how do I translate the "var result" of the lambda expression into a usable object that I can then print the result? I would also appreciate an in-depth explanation of what is happening when I declare the outer => outer.Value.Frequency (I've read numerous explanations of lambda expressions but additional clarification would help) C# //Input : {5, 13, 6, 5, 13, 7, 8, 6, 5} //Output : {5, 5, 5, 13, 13, 6, 6, 7, 8} //The question is to arrange the numbers in the array in decreasing order of their frequency, preserving the order of their occurrence. //If there is a tie, like in this example between 13 and 6, then the number occurring first in the input array would come first in the output array. List<int> input = new List<int>(); input.Add(5); input.Add(13); input.Add(6); input.Add(5); input.Add(13); input.Add(7); input.Add(8); input.Add(6); input.Add(5); Dictionary<int, FrequencyAndValue> dictionary = new Dictionary<int, FrequencyAndValue>(); foreach (int number in input) { if (!dictionary.ContainsKey(number)) { dictionary.Add(number, new FrequencyAndValue(1, number) ); } else { dictionary[number].Frequency++; } } var result = dictionary.OrderByDescending(outer => outer.Value.Frequency); // How to translate the result into something I can print??

    Read the article

  • Scheme define/lambda shorthand

    - by incrediman
    In Scheme, how can I make use of the define/lambda shorthand for nested lambda expressions within my define? For example given the following procedure... (define add (lambda (num1 num2) (+ num1 num2))) One can shorten it to this: (define (add num1 num2) (+ num1 num2)) However, how can I shorten the following function similarly ? (define makeOperator (lambda (operator) (lambda (num1 num2) (operator num1 num2)))) ;example useage - equivalent to (* 3 4): ((makeOperator *) 3 4)

    Read the article

  • Generic Sorting using C# and Lambda Expression

    - by Haitham Khedre
    Download : GenericSortTester.zip I worked in this class from long time and I think it is a nice piece of code that I need to share , it might help other people searching for the same concept. this will help you to sort any collection easily without needing to write special code for each data type , however if you need special ordering you still can do it , leave a comment and I will see if I need to write another article to cover the other cases. I attached also a fully working example to make you able to see how do you will use that .     public static class GenericSorter { public static IOrderedEnumerable<T> Sort<T>(IEnumerable<T> toSort, Dictionary<string, SortingOrder> sortOptions) { IOrderedEnumerable<T> orderedList = null; foreach (KeyValuePair<string, SortingOrder> entry in sortOptions) { if (orderedList != null) { if (entry.Value == SortingOrder.Ascending) { orderedList = orderedList.ApplyOrder<T>(entry.Key, "ThenBy"); } else { orderedList = orderedList.ApplyOrder<T>(entry.Key,"ThenByDescending"); } } else { if (entry.Value == SortingOrder.Ascending) { orderedList = toSort.ApplyOrder<T>(entry.Key, "OrderBy"); } else { orderedList = toSort.ApplyOrder<T>(entry.Key, "OrderByDescending"); } } } return orderedList; } private static IOrderedEnumerable<T> ApplyOrder<T> (this IEnumerable<T> source, string property, string methodName) { ParameterExpression param = Expression.Parameter(typeof(T), "x"); Expression expr = param; foreach (string prop in property.Split('.')) { expr = Expression.PropertyOrField(expr, prop); } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), expr.Type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, param); MethodInfo mi = typeof(Enumerable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), expr.Type); return (IOrderedEnumerable<T>)mi.Invoke (null, new object[] { source, lambda.Compile() }); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

    Read the article

  • Syntax of passing lambda

    - by Astara
    Right now, I'm working on refactoring a program that calls its parts by polling to a more event-driven structure. I've created sched and task classes with the sced to become a base class of the current main loop. The tasks will be created for each meter so they can be called off of that instead of polling. Each of the events main calls are a type of meter that gather info and display it. When the program is coming up, all enabled meters get 'constructed' by a main-sub. In that sub, I want to store off the "this" pointer associated with the meter, as well as the common name for the "action routine. void MeterMaker::Meter_n_Task (Meter * newmeter,) { push(newmeter); // handle non-timed draw events Task t = new Task(now() + 0.5L); t.period={0,1U}; t.work_meter = newmeter; t.work = [&newmeter](){newmeter.checkevent();};<<--attempt at lambda t.flags = T_Repeat; t.enable_task(); _xos->sched_insert(t); } A sample call to it: Meter_n_Task(new CPUMeter(_xos, "CPU ")); 've made the scheduler a base class of the main routine (that handles the loop), and I've tried serveral variations to get the task class to be a base of the meter class, but keep running into roadblocks. It's alot like "whack-a-mole" -- pound in something to fix something one place, and then a new probl pops out elsewhere. Part of the problem, is that the sched.h file that is trying to hold the Task Q, includes the Task header file. The task file Wants to refer to the most "base", Meter class. The meter class pulls in the main class of the parent as it passes a copy of the parent to the children so they can access the draw routines in the parent. Two references in the task file are for the 'this' pointer of the meter and the meter's update sub (to be called via this). void *this_data= NULL; void (*this_func)() = NULL; Note -- I didn't really want to store these in the class, as I wanted to use a lamdba in that meter&task routine above to store a routine+context to be used to call the meter's action routine. Couldn't figure out the syntax. But am running into other syntax problems trying to store the pointers...such as g++: COMPILE lsched.cc In file included from meter.h:13:0, from ltask.h:17, from lsched.h:13, from lsched.cc:13: xosview.h:30:47: error: expected class-name before ‘{’ token class XOSView : public XWin, public Scheduler { Like above where it asks for a class, where the classname "Scheduler" is. !?!? Huh? That IS a class name. I keep going in circles with things that don't make sense... Ideally I'd get the lamba to work right in the Meter_n_Task routine at the top. I wanted to only store 1 pointer in the 'Task' class that was a pointer to my lambda that would have already captured the "this" value ... but couldn't get that syntax to work at all when I tried to start it into a var in the 'Task' class. This project, FWIW, is my teething project on the new C++... (of course it's simple!.. ;-))... I've made quite a bit of progress in other areas in the code, but this lambda syntax has me stumped...its at times like thse that I appreciate the ease of this type of operation in perl. Sigh. Not sure the best way to ask for help here, as this isn't a simple question. But thought I'd try!... ;-) Too bad I can't attach files to this Q.

    Read the article

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