scala,functional-programming,fold

Solution 1 You could use the mkString function, which won't append the seperator at the end. In this case you first map each element to the corresponding String and then use mkString for putting the ',' inbetween. Since the "create X" is static in the beginning you could just prepend...

foldr can always be defined as: foldr f z t = appEndo (foldMap (Endo . f) t) z where appEndo and Endo are just newtype unwrappers/wrappers. In fact, this code got pulled straight from the Foldable typeclass. So, by defining foldMap, you automatically get foldr....

c++,c++11,template-meta-programming,fold

Until C++17 and fold expressions come along, a straightforward implementation of all_of is: // base case; actually only used for empty pack template<bool... values> struct all_of : std::true_type {}; // if first is true, check the rest template<bool... values> struct all_of<true, values...> : all_of<values...> {}; // if first is false,...

haskell,functional-programming,fold

You can do this using a list comprehension: length [ s | s <- someString, s `elem` notes] ...

foldr handles the recursion for you; you shouldn't be calling any? again inside of the lambda. Instead, the false branch can just be y. Or, a bit more obviously, perhaps: (define (any? procedure lst) (foldr (lambda (x y) (or (procedure x) y)) #f lst)) Additionally, the error you're getting is...

javascript,reduce,fold,associativity,commutativity

Doesn't it indeed make more sense for reduceRight to be implemented the way I did? Maybe. However, the JavaScript array iterators do not come from a pure functional programming background. Why is the native reduceRight not implemented the way I did? Because it's simpler (easier to remember) to have...

Here's a working version: fn main() { let z = (2..12).fold(vec![1u64, 1], |mut data, _| { let next = data[data.len()-2] + data[data.len()-1]; data.push(next); data }); println!("{:?}", z.last()) } There are a few problems with your approach: data: &mut Vec<uint> Your accumulator variable isn't a "reference to a mutable vector", it's...

I can see the following, a bit cryptic way of using foldl for your purpose (it is using zero-based indexing, but can be changed easily to 1-based): get i lst= snd $ foldl (\p (j, y) -> if j == i then (j,y) else p ) (0, 0) (zip [0,1..]...

scala,playframework-2.0,read-eval-print-loop,fold,iteratee

Scala's type inference isn't smart enough to say "oh, you wrote acc + ele and I know that acc is an integer, so ele must also be an integer". In context you often won't need the extra type annotation. For example, this compiles just fine: Enumerator(1, 2, 3).run(Iteratee.fold(0) { (acc,...

haskell,fold,type-mismatch,algebraic-data-types

A proper definition should consist of a pair of mutually recursive functions, one for folding trees and one for folding forests (lists of trees): foldtree :: (a -> c -> b) -> (b -> c -> c) -> c -> Treeof a -> b foldtree f g a (Node label...

This a less general answer, but it solves your original problem -- although its elegance is debatable. The main idea is the fact that generating a list with the reversed (as in ['file', 'user', 'home', '/'] order is quite easy, so you can just create that and reverse it in...

Because the function passed to foldr does not always evaluate the acc parameter, i.e. it is lazy in that parameter. For example, (\(k,v) acc -> if 1 == k then Just v else acc) (1,"one") (error "here be dragons!") will return "one" without even attempting to evaluate the error expression....

If you were to write out the calculation, it would look like this: x0 + 2 * x1 + 4 * x2 + 8 * x3 + ... This might suggest you need to use the index, but if you factorize this expression, you get this instead: x0 + 2...

Short Answer: No, Markdown does not offer a feature like that directly, but with some work you might be able to build something that works. For a feature like that to work you would need some CSS and/or JavaScript to control the animations, etc. While you might be able to...

This is a direct translation of your Scala code to Haskell: foldl (\acc x -> if x `mod` 3 == 1 then acc + 1 else acc) 0 [1..100] In Haskell, because of laziness of it, using foldl usually is not a good idea, a better choose is foldl' or...

Let's look at the relevant definitions (not exactly the same as the ones from the Prelude, but equivalent for this analysis). (&&) :: Bool -> Bool -> Bool True && x = x False && _ = False foldr :: (a -> b -> b) -> b -> [a] ->...

foldr takes a function of 2 arguments, but this doesn't prevent it from taking a function of 3 arguments provided that function has the right type signature. If we had a function g :: x -> y -> z -> w With foldr :: (a -> b -> b) ->...

Try the normal command. For this case you will need normal! to avoid recursive execution of your function.

Both foldr and foldl pass the list to the function with the arguments in the same order. foldr (+) 0 [1, 2, 3] = 1 + (2 + (3 + 0)) foldl (+) 0 [1, 2, 3] = ((0 + 1) + 2) + 3 That's all there is to...

You have the foldr evaluation backwards. It should look like this: foldr f 0 [1,2,3] == f 1 (f 2 (f 3 0)) For contrast, the foldl evaluation (which is correct in your question) looks like foldl f 0 [1,2,3] == f (f (f 0 1) 2) 3 If you...

In Notepad++ you can define a language by going to the Language menu --> Define your language (at least in version 6.6.9 anyway). On the Folder & Default tab, under Folding in code 1 style, input a ( into the "Open" box. Input a ) into the "Close" box. Save...

See output (scala 2.11): scala> def func = { println("Evaluate if empty"); (3,4)} func: (Int, Int) scala> val opt = Option((4,5)) opt: Option[(Int, Int)] = Some((4,5)) scala> opt.fold(func)( x => x) res7: (Int, Int) = (4,5) scala> opt.getOrElse(func) res8: (Int, Int) = (4,5) scala> val none:Option[(Int,Int)] = None none: Option[(Int,...

This is a pretty simple implementation: def elem[A](a: A, as: List[A]): Boolean = as match { case Nil => false case h :: t => (h == a) || elem(a, t) } Also, instead of find you could use exists: def elem[A](a: A, as: List[A]) = as.exists(_ == a) If...

clojure,parallel-processing,fold,reducers

Yes, reducers do solve this problem, because they have slightly different semantics from the type of fold that Guy Steele is referring to (although the effect can be very similar in practice). foldr and foldl take a single function argument, which is applied to each member of a collection (along...

haskell,recursion,fold,combinators

fold is strong enough; the trick is that we'll need to instantiate r as a reader monad of the current indentation level. fold :: ([r] -> r) -> (a -> r) -> (Tree a -> r) fold node leaf (Node children) = node (map (fold node leaf) children) fold node...

java,function,oop,signature,fold

By "fold" you probably mean "fold left", which is another name for "reduce". The Java Stream interface defines reduce, so I suggest inspecting that signature: T reduce(T identity, BinaryOperator<T> accumulator) ...

OK, so let's try this: step x acc = if isSpace x then if null (fst acc) then acc else ([], (fst acc) : (snd acc)) else (x : fst acc, snd acc) words' xs = snd $ foldr step ([], []) xs Now let's walk this through, one step...

Looks to be very simply a bug in that ancient(¹) version of boost. A quick bisection tells me it was fixed in v1.43.0(²). Release notes don't disclose the secret, but git does: c5621d9 MPL: merge fix for ticket #1992 boost::mpl::zip_view does not support use as a metafunction with ::type 31a2c78...

I'll start with some observations and hypotheses concerning the use of fold-expressions here. Essentially, we want to write a lexicographical comparison via a single fold-expression. We want to bail out of the comparisons once we can determine the result. Using a unary left fold (... OP comparison) evaluates to (...

First things first, I believe your foldl implementation is a bit off, the usual way to implement it in Scheme would be (but make sure to read @JoshuaTaylor's comment to understand the consequences): (define (foldl func accum lst) (if (null? lst) accum (foldl func (func (car lst) accum) ; here's...

You don't see a difference in your example because you chose a function such that for any x1 and x2: (acc - x1) - x2 = (acc - x2) - x1 So it doesn't matter in what order you go through the list, you will get the same result. List...

Right fold goes from right to left. Left fold goes from the left, like you read a text - from left to right....

haskell,clojure,functional-programming,fold

In Haskell: -- foldr f z xs == foldl (\r x a-> r (f x a)) id xs z zip1 xs ys = -- foldr f (const []) xs ys foldl (\r x a-> r (f x a)) id xs (const []) ys where f x r [] = []...

Here is a solution with for/fold: (define (n-grams/fold words n) (for/fold ([n-grams '()] [remaining-words words]) ([_ (in-naturals)] ; loop forever #:break (< (length remaining-words) n)) (values (cons (take remaining-words n) n-grams) (rest remaining-words)))) And here is one using foldl: (struct state (n-grams remaining-words) #:transparent) (define (n-grams/foldl words n) (foldl (λ...

The combinator you're describing (or at least something very similar) is often called mapAccum. Take the following simplified use of scanLeft: val xs = (1 to 10).toList val result1 = xs.scanLeft((1, 0.0)) { case ((acc, _), i) => (acc + i, i.toDouble / acc) }.tail.map(_._2) This is equivalent to the...

clojure,functional-programming,fold

Clojure implements a left fold called reduce. Why no right fold? reduce and many other functions work on sequences, which are accessible from the left but not the right. The new reducers and transducers are designed to work with associative functions on data structures of varying accessibility. ...

Some hints: You know that tails [] == [[]], so your initial value has to be [[]], so you'll have tails = foldr (\x y -> undefined : undefined) [[]] length (tails xs !! n) > length (tails xs !! (n+1)), or in plain english: the length of each tail...

haskell,fold,equational-reasoning

The foldr function is defined as follows: foldr :: (a -> b -> b) -> b -> [a] -> b foldr _ a [] = a foldr f a (x:xs) = f x (foldr f a xs) Now consider the following expression: foldr (\x y -> (x + y) *...

As to why your definition is not accepted: look at this: λ> :t \ x xs cont -> x : cont xs ... :: a -> r -> ((r -> [a]) -> [a]) λ> :t foldr foldr :: (a' -> b' -> b') -> b' -> [a'] -> b' so...

haskell,types,functional-programming,fold

Num [Int] => (Int -> Int -> Int) -> Int -> [Int] -> Int is a complete bogus signature. It means this: "provided any list of integers can be treated as a single number [??!], I give you a specialised version of a fold". That's no way like what you...

matlab,svm,fold,cross-validation

You can check wiki, In k-fold cross-validation, the original sample is randomly partitioned into k equal size subsamples. and The k results from the folds can then be averaged (or otherwise combined) to produce a single estimation. So no worries about different error rates of randomly selecting folds. Of course...

Applying the insight from my other answer, I was able to solve it, by defining two mutually-recursive types: -- tr ~ tq -> [(a,b)] -- tq ~ a -> tr -> [(a,b)] newtype Tr a b = PackR { unpackR :: Tq a b -> [(a,b)] } newtype Tq a...

About Q1: You have to somehow skip over the elements in the list which are not positive numbers. One idea is to first filter them out, as Chris shows. An alternative would be to filter them out with foldl itself: (define (product-of-positives lst) ; pass input list as parameter (foldl...

function,haskell,parameters,arguments,fold

Is this what you are looking for? break (\x -> x == ' ' || x == '\t' || x == '\n') xss ...

placeholders.foldLeft(PlaceHolder(0,0,0))((acc, p) => PlaceHolder(acc.time + p.time, acc.a + p.a, acc.b + p.b)) or placeholders.reduce((acc, p) => PlaceHolder(acc.time + p.time, acc.a + p.a, acc.b + p.b)) or you could add a + operator to PlaceHolder: case class PlaceHolder(time: Long, a: Int, b: Int) { def +(other: PlaceHolder) = PlaceHolder(this.time + other.time,...

delete is a modal search. It has two different modes of operation - whether it's already found the result or not. You can use foldr to construct a function that passes the state down the line as each element is checked. So in the case of delete, the state can...