FAQ Database Discussion Community


Why use Object.create inside this reduce callback?

javascript,functional-programming
So while working on #19 of this fine tutorial - http://jhusain.github.io/learnrx/, I find that the exercise works without using Object.create. (See the commented-out lines) 1. So what is the point of creating that copy of the accumulatedMap? Other than showing that it is possible... function() { var videos = [...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?

scope,functional-programming,lazy-evaluation
I apologize if this has an obvious answer. I would like to find a lazy functional programming language where the following pseudo code makes sense: let f = function(x) { let y = x*x // The variables y and z let z = y*2 // are local return z }...

Functional way of finding inverse ranges

javascript,regex,functional-programming,templating
I'm writing a templating utility for a library and trying to do it in a functional way (no mutable variables and ideally no intermediate state). This is mainly a learning exercise and I know there are libraries out there that do this already. Given the string: "Hello, {{name}}! What are...

Trial division for primes with immutable collections in Scala

algorithm,scala,data-structures,functional-programming
I am trying to learn Scala and functional programming ideology by rewriting basic exercises. Currently I have trouble with naive approach for generating primes "trial division". The trouble described below is that I could not rewrite well-known algorithm in functional style preserving efficiency, because I have no suitable immutable data...

OO way or functional way of string comparison conditionals in php

php,oop,functional-programming
I am curling on a specific page that returns only html. To determine what page it returns, I simply try to stripos the result of the curl Like so: $result = curl_exec($ch); if(stripos($result, 'success') !== false) { // do something } else { if (stripos($result, 'foo') !== false) { //...

How to effectively get indices of 1s for given binary string using Scala?

scala,functional-programming,higher-order-functions
Suppose we have a binary string such as 10010010. All I want is a function returning indices of 1s for that string: indicesOfOnes("10010010") -> List(0, 3, 6) indicesOfOnes("0") -> List() And what I implemented is: def indicesOfOnes(bs: String): List[Int] = { val lb = ListBuffer[Int]() bs.zipWithIndex.foreach { case (v, i)...

What is the intuition behind the checkerboard covering recursive algorithm and how does one get better at formulating such an algorithm?

python,algorithm,recursion,functional-programming,induction
You may have heard of the classic checkerboard covering puzzle. How do you cover a checkerboard that has one corner square missing, using L-shaped tiles? There is a recursive approach to this as explained in the book "Python Algorithms Mastering Basic Algorithms in the Python Language." The idea is to...

Assigning unique variable from a data.frame

r,function,functional-programming,unique,identity-column
This is a similiar question to this but my output results are different. Take the data: example <- data.frame(var1 = c(2,3,3,2,4,5), var2 = c(2,3,5,4,2,5), var3 = c(3,3,4,3,4,5)) Now I want to create example$Identity which take a value from 1:x for each unique var1 value I have used example$Identity <- apply(example[,1],...

A seemingly silly way of using the Stream API that leads to the need for Predicate

functional-programming,java-8,java-stream
A predicate on booleans seems a little silly to me (well, at least in the following scenario): static Set<A> aSet = ...; checkCondition(B b) { return aSet.stream() .map(b::aMethodReturningBoolean) .filter((Boolean check) -> check) .limit(1).count() > 0; } What I am doing is that given the object b, checking whether there is...

Functional way of doing a loop of operations on an array

java,scala,functional-programming
I currently have a Java program which does something like the following: int nvars = 10; long vars[] = new long[nvars]; for(int i = 0; i < nvars; i++) { vars[i] = someFunction(i); anotherFunction(vars[i]); } I am converting it into Scala code and have: val nvars: Int = 10 val...

Lazy concat in Immutable.js?

javascript,functional-programming,immutable.js
Is there a way to do a lazy concat of two sequences in Immutable.js? Specifically, I have this algorithm that flattens a tree into a breadth-first sequence: var Immutable = require('immutable'); var tree = { value: 'foo', children: [ { value: 'bar', children: [ { value: 'barOne'}, { value: 'barTwo'}...

Convert loop to Maybe monad

c#,functional-programming,maybe
Recently I tried applying Maybe monad pattern in my C# code using this library. What I found difficult to grasp was converting such a function into Maybe paradigm: public Maybe<object> DoSomething(IReader reader) { while (true) { var result = reader.Read(); if (result == null) return Maybe<object>.Nothing; if (result.HasValue) return new...

Why is 'window.angular' used like so, in this function definition?

javascript,angularjs,functional-programming
I'm trying to understand an angularjs file I need to use to integrate with Django, and it has a weird syntax I'm not familiar with (bear in mind I'm a junior dev, so this may be your bread and butter)... It goes something like: (function(angular, undefined){ 'use script'; var djng_forms_module...

A little confusion with the sorted function in Haskell

haskell,recursion,functional-programming
sorted :: Ord a => [a] -> Bool sorted xs = and [x <= y | (x,y) <- pairs xs] Can anyone explain to me what this random and is doing after =? It works when I compile it but it doesn't make logical sense to me. Is it because...

Is there a functional way to set a variable in javascript?

javascript,functional-programming
I am looking for something like this: set("variablename", "value"); Why I need this? I want to write the following without creating a new function: navigator.getUserMedia({ audio: true }, success, fail); var success = function(stream) { var source = audioCtx.createMediaStreamSource(stream); } ...

How to get a Column from a Frame as a double array type in Deedle C#?

c#,functional-programming,deedle
I wish to extract a column from a frame as a new double array in C#. For example: double[] values = myFrame.GetColumn<double>("myColumnName"); ...

Why is `++` for Haskell List implemented recursively and costs O(n) time?

list,pointers,haskell,recursion,functional-programming
As I understood, a List in Haskell is a similar to a Linked-List in C language. So for expressions below: a = [1,2,3] b = [4,5,6] a ++ b Haskell implement this in a recursive way like this: (++) (x:xs) ys = x:xs ++ ys The time complexity for that...

Deep changing values in a JavaScript object

javascript,recursion,data-structures,functional-programming,mootools
I have an object which contains an unknown number of other objects. Each (sub-)object may contain boolean values as strings and I want to change them to real boolean values. Here's an example object: var myObj = { my1stLevelKey1: "true", my1stLevelKey2: "a normal string", my1stLevelKey3: { my2ndLevelKey1: { my3rdLevelKey1: {...

returning functions in R - when does the binding occur?

r,function,functional-programming,lazy-evaluation
As in other functional languages, returning a function is a common case in R. for example, after training a model you'd like to return a "predictor" object, which is essentially a function, that given new data, returns predictions. There are other cases when this is useful, of course. My question...

Apply a list of Functions to a Java stream's .map() method

java,lambda,functional-programming,java-8,java-stream
I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this: List<NameValuePair> paramPairs = getParamPairs(); List<NameValuePair> newParamPairs = paramPairs.stream() .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp)) .flatMap(Collection::stream) .collect(toList()); But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions....

LISP: read number from user and commpare with array index

functional-programming,lisp,common-lisp
Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare...

Kind Classification of Types

haskell,functional-programming
In Benjamin Pierce's book on Types and Programming Languages he classifies the different kinds of types as follows: * the kind of proper types (like Bool and Bool -> Bool) * -> * the kind of type operators (i.e., functions from proper types to proper types) * -> * ->...

Scala wrong forward reference

scala,functional-programming
I am working through some of the exercises in: Functional Programming in Scala specifically problem 5.2. The issue is that with the following code which I have pieced together from the answer key. sealed trait Stream[+A] { def take(n: Int): Stream[A] = this match { case Cons(hs, ts) if n...

How do you represent nested types using the Scott Encoding?

haskell,functional-programming,lambda-calculus,algebraic-data-types,scott-encoding
An ADT can be represented using the Scott Encoding by replacing products by tuples and sums by matchers. For example: data List a = Cons a (List a) | Nil Can be encoded using the Scott Encoding as: cons = (λ h t c n . c h t) nil...

How to rewrite Erlang combinations algorithm in Elixir?

functional-programming,erlang,elixir
I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck. Erlang version: comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T). Elixir version I came up with...

How to get only specific elements of list in racket

functional-programming,scheme,racket
Input: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73) ("june 101" 55 55) ("june 104" 55 54) ("aug 201" 220 220)) Desired output: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73)) How do I achieve this? I only want the may terms....

How to re-create Underscore.js _.reduce method?

javascript,functional-programming,underscore.js,reduce
For education purposes, I was trying to re-create Underscore.js's _.reduce() method. While I was able to do this in an explicit style using for loops. But this is far from ideal because it mutates the original list that was supplied as an argument, which is dangerous. I also realized that...

To “combine” functions in javascript in a functional way?

javascript,functional-programming
I'm learning functional programming and I wonder if there is a way to "combine" functions like this: function triple(x) { return x * 3; } function plusOne(x) { return x + 1; } function isZero(x) { return x === 0; } combine(1); //1 combine(triple)(triple)(plusOne)(1); // 10 combine(plusOne)(triple)(isZero)(-1); // true If...

Apply successive filters to an array in Ruby

ruby,functional-programming
I have an array of some objects, perhaps strings or numbers. I want to apply some arbitrary filters to this array, and I want to be able to specify the order of the filters. Here's an example (I know that in this toy example, order doesn't matter, but I want...

Java 8 Lambda expressions for solving fibonacci (non recursive way)

java,lambda,functional-programming,java-8
I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc. However can they be utilized effectively in solving problems like Fibonacci where the current value depends on sum of previous two values. I...

Creating a filterable list with RxJS

javascript,functional-programming,reactive-programming,rxjs,reactive-extensions-js
I'm trying to get into reactive programming. I use array-functions like map, filter and reduce all the time and love that I can do array manipulation without creating state. As an exercise, I'm trying to create a filterable list with RxJS without introducing state variables. In the end it should...

Is there any formula that maps an int on the range [0..πR²] to the (x,y) coordinates inside the circle of radius R?

algorithm,math,language-agnostic,functional-programming,formula
The formula: index(i,w,h) = (i%w, (i/w)%h) uniquely maps each integer i on the range [0..w*h] to a coordinate inside the rectangle of width w and height h. Is there any similar formula: index(i,r) = ? that uniquely maps each integer on the range [0..πR²] to a coordinate inside the circle...

How to generate data idiomatically in f# inline in code

f#,functional-programming,immutability,poker
Lets say i am attempting to implement some sort of poker program in f#. Firstly is this the correct use of the type system, massive newbie here. type Suit = | Hearts | Diamonds | Spades | Clubs type Card = { Suit:Suit Rank:int } type Hand = { Cards:List<Card>...

Semantically correct way to modify a Ruby hash - a functional approach?

ruby,hash,functional-programming
I have to clean up a object in Ruby, and the way I have been doing that is by cloning a hash, and modifying an original. This was my original method: def remove_empty_stories(content) content.clone.each do |section,stories| for i in 0...stories.length do if stories[i].length < 25 content[section].delete_at(i) end end end content...

Cycling through a vector whose elements are inputs to another function in R

r,functional-programming,combinations
I need to apply all the combinations of the elements of a vector to a particular function, and use these elements as inputs for this function as well. I would like it to be somewhat fast, but any combination of apply and its different flavors has proved fruitless so far....

Questions about Vars Clojure

clojure,functional-programming
I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable? I can change the value of the var after, so is it really that different...

Is memoizing possible without side effects

f#,functional-programming,memoization,side-effects
I have some F# code that caches results for future lookup. My understanding is that dictionaries and other data structures that you add to require side effects. (i.e. changing the state of the dictionary) Is this correct? Is this considered impure or is this still in the model of side...

Lazy functions evaluation in swift

ios,swift,if-statement,functional-programming,lazy-evaluation
Wondering is it possible to evaluate a simple if statement lazily. Below is an example that will print "this is foo" and "this is bar", but I really want to make it print only the first string: func foo() { println("this is foo") } func bar() { println("this is bar")...

How are point-free functions actually “functions”?

haskell,functional-programming,pointfree
Conal here argues that nullary-constructed types are not functions. However, point-free functions are described as such for example on Wikipedia, when they take no explicit arguments in their definitions, and it seemingly is rather a property of currying. How exactly are they functions? Specifically: how are f = map and...

Create array using _.each

javascript,arrays,functional-programming,underscore.js,each
I've this exercise to solve: Use _.each to create an array from 1, 1000 (inclusive) I really don't know how to do that and i'm thinking it's not possible... Can you help me?...

How to rewrite this code in Scala using a Functional Programming approach

scala,functional-programming
Below is code snippet that does some URL normalization. How to rewrite it to use immutable variables only? Of course, without making it larger or more complex. private def normalizeUrl(url0: String) = { var url = url0 if (url.endsWith("/")) { url = url.dropRight(1) } if (url.indexOf(':') < 0 || url.indexOf(':')...

Is this definition of a tail recursive fibonacci function tail-recursive?

scala,f#,functional-programming,tail-recursion,continuation-passing
I've seen around the following F# definition of a continuation-passing-style fibonacci function, that I always assumed to be tail recursive: let fib k = let rec fib' k cont = match k with | 0 | 1 -> cont 1 | k -> fib' (k-1) (fun a -> fib' (k-2)...

F# Observable - Converting an event stream to a list

f#,functional-programming,reactive-programming,observable
I was writing an unit test that verified the events fired from a class. I followed the standard "IEvent<_>, Publish, Trigger inside an FSharp type" pattern. Can you recommend the "functional" way to achieve that? Here are the options I can think of: Convert the event stream into a list...

Mapping a vector of one type to another using lambda

c++,c++11,lambda,functional-programming
I have a bit of code that looks like B Convert(const A& a) { B b; // implementation omitted. return b; } vector<B> Convert(const vector<A>& to_convert) { vector<B> ret; for (const A& a : to_convert) { ret.push_back(Convert(a)); } retun ret; } I was trying to rewrite this using lambdas but...

Is there a better way to implement a functional recursive findById in javascript than this?

javascript,functional-programming
I dislike loops, however this seems easy to solve with a loop and hard using functional programming. Here's the loop version: for(var i = 0; i < collection.length; i++) { var result = collection[i].findById(id); if (result) { return result; } } Since this is a common pattern, I expected to...

What is the type of the variable in do-notation here in Haskell?

haskell,functional-programming,monads,do-notation
The codes below looks quite clear: do x <- Just 3 y <- Just "!" Just (show x ++ y) Here the type of x is Num and y is String. (<- here is used to take actual value out of the Monad) However, this snippet looks not so clear...

Elm List type mismatch

list,functional-programming,elm
I was following an (old?) tutorial and I got a type mismatch. Has the List library changed from 0.14.1 to 0.15? elmpage. Code: module Fibonacci where import List exposing (..) fibonacci : Int -> List Int fibonacci n = let fibonacci1 n acc = if n <= 2 then acc...

Computing a term of a list depending on all previous terms

haskell,recursion,functional-programming,lazy-evaluation,formal-methods
I have the following identity, that defines (implicitly) the number of partitions of positive integers (that is, the number of ways you can write the integer as the sum of ordered positive nonzero integers): Some notes: This is studied in the book Analytic Combinatorics by Flajolet and Sedjewick, and the...

How is `each` different from `for-loop` when returning a value?

javascript,functional-programming,find,each
I have my each function which I created to emulate Underscore.js's _each() for my Javascript study. var each = function(list, iteratee) { if (Array.isArray(list)) { // list is array for (var i = 0; i < list.length; i++) { iteratee(list[i], i, list); } } else if (list.constructor === Object) {...

Sum of Fibonacci term using Functional Swift

swift,functional-programming
I'm trying to learn functional Swift and started doing some exercises from Project Euler. Even Fibonacci numbers Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5,...

Hook into GHC runtime system

haskell,functional-programming,runtime,transactional-memory
I have been looking at how transactional memory is implemented in Haskell, and I am not sure I understand how the STM operations exposed to the programmer hook into the runtime system functions written in C. In ghc/libraries/base/GHC/Conc/Sync.hs of the git repo, I see the following definitions: -- |A monad...

confused about return array#map javascript [duplicate]

javascript,arrays,functional-programming
This question already has an answer here: Can anyone explain why linebreaks make return statements undefined in JavaScript? 4 answers I have the code: function func1(){ return array.map(function(el){ return el.method(); }); } function func2(){ var confused = array.map(function(el){ return el.method(); }); return confused; } Why func1 return undefined while...

Spray routing filter path parameter

scala,functional-programming,akka,spray
given this snippet of code val passRoute = (path("passgen" / IntNumber) & get) { length => complete { if(length > 0){ logger.debug(s"new password generated of length $length") newPass(length) } else { logger.debug("using default length 8 when no length specified") newPass(8) } } } How could I replace the if-else with...

Apply a list of parameters to a curried function

functional-programming,sml,currying
simple task: all I want is a function to apply a list of parameters to a curried function. Let's say our function is the famous add one: fun add a b = a + b; Now all I want is a function to apply a list (say [1, 5]) to...

How to handle initial nil value for reduce functions

swift,functional-programming,reduce
I would like to learn and use more functional programming in Swift. So, I've been trying various things in playground. I don't understand Reduce, though. The basic textbook examples work, but I can't get my head around this problem. I have an array of strings called "toDoItems". I would like...

First word of binary string erlang

functional-programming,erlang,pattern-matching
I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Remove item from array using foreach - JavaScript [duplicate]

javascript,functional-programming
This question already has an answer here: How do I remove an element in a list, using forEach? 2 answers Is it possible to remove something from an array using foreach? var array = [1,2,3,4,5,6,7,8]; array.forEach(function(data){ if (data == 4) { // do something here } }); console.log(array); ...

What is monad analog in Java?

java,scala,functional-programming
I know in Scala and many other functional languages there are monads that is mostly just an interface realization(for example in Scala with flatMap[T] and unit[T] methods) is there are any Java-style interfaces that could be a monad?

Using Diagrams library in haskell (draw binary trees)

haskell,recursion,tree,functional-programming,binary-tree
I am trying to use the Haskell Diagrams library for drawing binary trees. This is my tree type: data Tree a = Empty | Node { label :: a, left,right :: Tree a } leaf :: a -> Tree a leaf a = Node a Empty Empty This is a...

Why prefer Typeclass over Inheritance?

scala,inheritance,functional-programming,typeclass
According to this Erik Osheim's slide, he says the inheritance can solve the same problem as typeclass would, but mentions that inheritance has a problem called: brittle inheritance nightmare and says the inheritance is tightly coupling the polymorphism to the member types What is he means? In my opinion, Inheritance...

Properly implement F# Unit in C#

c#,f#,functional-programming
This question is not about C#/F# compatibility as in this one. I'd like to know the proper way to implement a type like F# Unit in place of using void. Obviously I'll discard this result and I'll not expose this type to the outside world. Wondering if an empty class...

Swift: Avoid imperative For Loop

swift,ios8,functional-programming
What I'm trying to accomplish in imperative: var mapNames = [String]() var mapLocation = [String]() for valueMap in valueMaps { if let name = valueMap.name { mapNames.append(name) } if let location = valueMap.location { mapLocation.append(location) } } What's the best way using a high order function or perhaps an array...

Declaring a Ruby lambda with a yield

ruby,lambda,functional-programming
I'm writing a method that splits an array of struct into a couple of different, arrays while also eliminating elements with nil values. What I want to write is: def my_func(some_data) f = lambda{|data| data.select{|m| yield(m).present? }.map { |m| [m.date, yield(m)]}} x = f.call(some_data) {|m| m.first_var} y = f.call(some_data) {|m|...

Joining a collection based on members of the type

java,functional-programming,guava,method-chaining
I have a class A and its members b and c. Now I construct the List<A> with this: add(new A().setb("abcd").setc("123456")); add(new A().setb("efgh").setc("789101")); add(new A().setb("ijkl").setc("112345")); I want to transform this List to string which looks like this abcd,123456 efgh,789101 ijkl,112345 Now the very obvious way would be to have a StringBuilder...

Java stream of optionals to optional stream

java,functional-programming
I need to convert Stream<Optional<Integer>> to Optional<Stream<Integer>>. The output Optional<Stream<Integer>> should be an empty value when at least one value ofStream<Optional<Integer>> is empty. Do you know any functional way to solve the problem? I tried to use collect method, but without success....

Grouping a range of integers to the answer of a function

java,functional-programming,java-8,java-stream
For a range of integers, I would like to apply an ("expensive") operation, filter out only those integers with interesting answers, then group on the answer. This first snippet works, but it duplicates the operation ("modulus 2") both in code and computation: IntStream.range(1, 10).boxed() .filter(p -> (p % 2 !=...

Having trouble stepping through function that reduces an array of functions

javascript,functional-programming,reduce,higher-order-functions
When using the reduce method on an array of functions I am having difficulty tracing through how reduce works on the array exactly. comboFunc(num, functionsArr) { return functionsArr.reduce(function (last, current) { return current(last); }, input); } so with functionsArr = [add, multi] and the functions add and multi being function...

Easier way to apply multiple arguments in Haskell

haskell,functional-programming,composition,functor,applicative
Given value f with type :: Applicative f => f (a -> b -> c), What's the best way to map arguments to the inner function. So far I've found the following: (\x -> x a b) <$> f (flip ($ a) b) <$> f ($ b) <$> ($ a)...

Functional way of programming in Java 1.7 [closed]

java,functional-programming
Is it possible to code application in functional programming way without using Java 8 and other 3rd party library? I mean to ask that if we follow some design patterns can that help us achieve functional programming paradigm in Java 1.7 I am not much experienced with design patterns, i...

In underscore/lodash, how to avoid duplicate calculation in a `map` method?

javascript,functional-programming,underscore.js,lodash
Here is my code: var transformed = _(original).map(function (c) { return { lat: wgs2gcj(c.latitude, c.longitude).lat lng: wgs2gcj(c.latitude, c.longitude).lng } }); Let's say wgs2gcj is a function from a third-party library and will take a long time to compute. Is there a way to do the calculation only once?...

for vs map in functional programming

scala,functional-programming
I am learning functional programming using scala. In general I notice that for loops are not much used in functional programs instead they use map. Questions What are the advantages of using map over for loop in terms of performance, readablity etc ? What is the intention of bringing in...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java
Abstract idea I want to get the first value coming out of a set of Futures, that satisfies a given predicate. If a satisfying value is found, all other Futures should be cancelled. If no value is found after all Futures have returned the execution should be terminated (by returning...

Functional Breadth First Search

python,haskell,functional-programming,ocaml,sml
Functional depth first search is lovely in directed acyclic graphs. In graphs with cycles however, how do we avoid infinite recursion? In a procedural language I would mark nodes as I hit them, but let's say I can't do that. A list of visited nodes is possible, but will be...

What is Anamorphism - example in C#

c#,functional-programming,catamorphism
I am trying to wrap my head around the concept of anamorphism. In functional programming, an anamorphism is a generalization of the concept of unfolds on lists. Formally, anamorphisms are generic functions that can corecursively construct a result of a certain type and which is parameterized by functions that determine...

Standard ML / NJ: Loading in file of functions

functional-programming,sml
I'm trying to write a bunch of functions in an SML file and then load them into the interpreter. I've been googling and came across this: http://www.smlnj.org/doc/interact.html Which has this section: Loading ML source text from a file The function use: string -> unit interprets its argument as a file...

Why is there no “Functor” trait in Scala? [closed]

scala,haskell,functional-programming,functor
In Scala, the generic classes such as Future, Option and List all have methods map and flatMap. As I understand, all of them are like Functors in Haskell. I was just wondering why there isn't a trait (interface) called Functor in Scala.. Does anyone have ideas about this?...

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching
Is there an elegant way to do something like the following example using just one case statement? foobar match { case Node(Leaf(key, value), parent, qux) => { // Do something with parent & qux } case Node(parent, Leaf(key, value), qux) => { // Do something with parent & qux (code...

Does for..in loop keeps track of orders of its properties for Object?

javascript,arrays,object,functional-programming,reduce
I'm a beginner for programming in general, and JavaScript is my first language. While I was studying, I faced with this concern, and I'm not sure if my concern is appropriate. I thought for..in loop does not keep track of orders when we loop through an Object, because, unlike Arrays,...

How to implement this simple algorithm elegantly in Scala

list,scala,functional-programming
I would like to have an elegant implementation of the method with the following (or similar) signature: def increasingSubsequences(xs: List[Int]): List[List[Int]] What it does is it splits the input sequence without reordering the elements so that every subsequence in the result is strictly increasing. I implemented it myself as follows:...

Determine the arity of a function handle and currying

matlab,functional-programming,currying,arity
Is there any way to determine the arity of a function and/or curry functions in MATLAB? I can't find any documentation on the matter.

Why would my find method return undefined?

javascript,functional-programming,find,each
I'm recreating a number of Underscore.js methods to study JavaScript and programming in general. Below is my attempts to recreate Underscore's _.find() method. var find = function(list, predicate) { // Functional style _.each(list, function(elem){ if (predicate(elem)) { return elem; } }); }; var find = function(list, predicate) { // Explicit...

functional way to accumulate pairs in java8

java,functional-programming,java-8,java-stream
Here's some imperative code that I'm trying to translate into functional programming code: public class Person { String name; Token token; public Person(String name, Token token) { this.name = name; this.token = token; } } public class Token { String id; boolean isValid; public Token(String id, boolean isValid) { this.id...

in clojure, function argument type mismatch

clojure,functional-programming,lisp
clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Lodash equals function

javascript,functional-programming,underscore.js,lodash
I need to make several operations with given map: var keys = { a: 1, b: 2, c: 1, d: 2, e: 2 } _.findKey(keys, function(value) { return value === 2; }); // "b" _.omit(keys, function(value) { return value === 2; }); // {a: 1, c: 1} I want to...

In simplest term, what is currying and why should this approach be favored over traditional programming paradigm?

scala,functional-programming,software-engineering,currying
I am having hard time understanding currying through several sources on web . Isn't there more intuitive example of currying? Also, what are its advantages over traditional programming paradigm ? Is currying possible to achieve on non-functional programmming?...

Order items based on an other field MySQL

php,mysql,functional-programming
I have a music theme for wordpress which has album listing page, albums are sorted ASC or DESC. I want the albums to be sorted based on another field which is a post_modified As I am new in PHP and programming can not figure it out self. I am pasting...

Idiomatic exception handling for socket connection

scala,sockets,error-handling,functional-programming,try-with-resources
I'm trying to understand how I can elegantly use scala.util.control.Exception package. To be more specific I want to convert this piece of Java code to functional way: public static boolean hostAvailabilityCheck() { try (Socket s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT)) { return true; } catch (IOException ex) { /* ignore */...

Java 8 streaming API using with Map

lambda,functional-programming,java-8,java-stream
I see this code snippet at my work. I am unable to get correct picture of what is going on here. I tried using debugger to get values, but debugger is not helpful here. public static void process (ErrorCat exc, String toFind) { Map<String, Function<Error, Error>> translate = new HashMap<>();...

Elm: understanding foldp and mouse-clicks

functional-programming,elm
I'm currently learning Elm. relatively new to functional programming. i'm trying to understand this example from http://elm-lang.org/learn/Using-Signals.elm on counting mouse-clicks. they provide the following code: clickCount = foldp (\click count -> count + 1) 0 Mouse.clicks They explain that foldp takes three arguments: a counter-incrementer, which we defined as an...

Accessing call stack depth in Scheme

functional-programming,scheme,tail-recursion,callstack
In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

Haskell function that accepts function or value, then calls function or returns value

haskell,functional-programming
How can I write a type declaration and function in Haskell that takes either a function (that itself takes no arguments) or a value. When given a function it calls the function. When given a value it returns the value. [edit] To give more context, I'm mostly curious how to...

In Scala, is there an equivalent of Haskell's “fromListWith” for Map?

scala,haskell,functional-programming
In Haskell, there is a function called fromListWith which can generate a Map from a function (used to merge values with the same key) and a list: fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a The following expression will be evaluated...

F# pass by reference

f#,functional-programming,pass-by-reference,out,ref
I'm trying to pass by reference in F#. In C#, it is pretty easy using the ref and out keywords, but it seems in F#, it is not that simple. I just read this: http://davefancher.com/2014/03/24/passing-arguments-by-reference-in-f/, which suggests using a reference cell. (I suppose this means there is no analog to...

Purity, Referential Transparency and State Monad

scala,functional-programming
I'm currently designing a numerical algorithm which as part of its operations requires updating a vector of doubles many times. Due to the fact that the algorithm has to be as space and time efficient as possible, I do not want to code the traditional type of FP code which...

Generating Custom Object from ArrayList in C# at runtime

c#,asp.net,.net,dynamic,functional-programming
I have the following content stored in ArrayList as pure string each line represents the value of an item in the list , is there a way to generate a dynamic object in the following style : [left operand is the property] = [right operand is the value of that...

why the interpreter tell me “This kind of expression is not allowed as right-hand side of `let rec'”

functional-programming,ocaml
I write a ocaml program that parse an arithmetic expression by parser combinator. type 'a parser = char list -> ('a * (char list)) list let return (x: 'a): 'a parser = fun input -> [x, input] let fail: 'a parser = fun _ -> [] let ( >>= )...

Evaluate a list of functions in Clojure

clojure,functional-programming,clojurescript
I have a list of functions which have no side-effects and take the same arguments. I need to evaluate each function in my list and put the results into another list. Is there a function in Clojure that does it?

Idiomatic list construction

list,haskell,functional-programming,idiomatic
I'm very new to Haskell and functional programming in general, so I don't really know how to make this code idiomatic: type Coord = Double data Point = Point Coord Coord Coord deriving Show type Polyline = [Point] -- Add a point to a polyline addPoint :: Polyline -> Point...

Turn object into array, add object as new element

javascript,functional-programming,underscore.js,lodash
Trying to transform an object of objects: var items: { item_a: { state: 'item_a status' }, item_b: { state: 'item_b status' } }; into an array of objects, whilst adding a new array element to the object (the object key): var items = [{ name: 'item_a', state: 'item_a status' },...

Erlang syntax error unclear

function,variables,if-statement,functional-programming,erlang
I just got started with Erlang. I am trying if statement. I found out one particular behavior which I do not understand. the following statement does work perfectly. some_comp(Arg1) -> if (cal(Arg1)>50000)->'reached'; true -> 'invalid' end. cal(Arg2)-> %% some calculation. However the following shows an error syntax near if: some_comp(Arg1)...