Menu
  • HOME
  • TAGS

Standard ML / NJ: Loading in file of functions

functional-programming,sml

As you mentioned, the function use has type string -> unit. This means it takes a string and returns unit. When you do use test.sml, you are not giving it a string. You need to do use "test.sml" (notice the quotes)

confused about return array#map javascript [duplicate]

javascript,arrays,functional-programming

Internally in JS engine first example looks like this, function func1() { return; array.map(function(el){ return el.method(); }); }; that's why you get undefined, don't add new line after return, because return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that...

Collapse similar case statements in Scala

scala,functional-programming,pattern-matching

You can use a custom extractor to abstract the matching part away from the logic part: object Leafed { def unapply(tree: Tree) = tree match { case Node(Leaf(_, _), parent, qux) => Some((parent, qux)) case Node(parent, Leaf(_, _), qux) => Some((parent, qux)) case _ => None } } And then...

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

java,lambda,functional-programming,java-8,java-stream

If lookupFunction(nvp.getName()) returns a Collection of functions, you can get a Stream of that Collection and map each function to the result of applying it to the NameValuePair : List<NameValuePair> newParamPairs = paramPairs.stream() .flatMap((NameValuePair nvp) -> lookupFunction(nvp.getName()).stream().map(func -> func.apply(nvp))) .flatMap(Collection::stream) .collect(toList()); ...

Joining a collection based on members of the type

java,functional-programming,guava,method-chaining

Solved it!! Lets say the List<A> is called Alist String join=Joiner.on("\n").skipNulls().join(Iterables.transform(Alist, new Function<A,String>(){ public String apply(A input){ return input.getb()+","+input.getc(); } })); ...

How to rewrite Erlang combinations algorithm in Elixir?

functional-programming,erlang,elixir

You need to wrap the for expression in parentheses like the Erlang code. def combination(n, [x|xs]) do (for y <- combination(n - 1, xs), do: [x|y]) ++ combination(n, xs) end Demo: iex(1)> defmodule Foo do ...(1)> def combination(0, _), do: [[]] ...(1)> def combination(_, []), do: [] ...(1)> def combination(n,...

How do you represent nested types using the Scott Encoding?

haskell,functional-programming,lambda-calculus,algebraic-data-types,scott-encoding

If the Wikipedia article is correct, then data Tree a = Node (List (Tree a)) | Leaf a has Scott encoding node = λ a . λ node leaf . node a leaf = λ a . λ node leaf . leaf a It looks like the Scott encoding is...

LISP: read number from user and commpare with array index

functional-programming,lisp,common-lisp

Common Lisp is multi-paradigm, not purely functional. There's really no reason to change your code algorithm from C#. If you want to write in a procedural style, you can continue to do so. (defun main (&rest args) (declare (ignore args)) (loop (princ "Enter the number:") (finish-output) (let ((name (read-line)) (numbers...

What is Anamorphism - example in C#

c#,functional-programming,catamorphism

LINQ's Aggregate method has the signature T Aggregate<T>(IEnumerable<T> source, Func<T, T, T> accumulator) So the corresponding unfolding would be IEnumerable<T> Unfold<T>(T seed, Func<T, Nullable<T>> accumulator) { Nullable<T> nextValue = new Nullable<T>(seed); while (nextValue.HasValue) { yield return nextValue.Value; nextValue = accumulator(nextValue); } } In functional programming, folding and unfolding must include...

Using Diagrams library in haskell (draw binary trees)

haskell,recursion,tree,functional-programming,binary-tree

I think the problem is you're naming giving the inner nodes the same names so connectOutside connects the first names it finds (which happen to be the last nodes in your tree). You can solve this by giving each node a unique name depending on its position: diagTree :: Show...

How to generate data idiomatically in f# inline in code

f#,functional-programming,immutability,poker

One way to shuffle a deck would be to zip it with a sequence of random numbers, then sort by those numbers, then unzip again. let allCards = [ for rank in 2..14 do for suit in [Hearts; Diamonds; Spades; Clubs] do yield { Suit = suit; Rank = rank...

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

scala,functional-programming,higher-order-functions

You can use a filter and then map to get the index : scala> val s = "10010010" s: String = 10010010 scala> s.zipWithIndex.withFilter(_._1 == '1').map(_._2) res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 3, 6) Note: I'm using withFilter and not filter to avoid creating a temporary collection. Or you can use collect,...

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

r,functional-programming,combinations

This looks like a job for the reval package! First, generate the parameter sets (see Generating all distinct permutations of a list in R and data.frame rows to a list): all <- expand.grid(0:2, 0:2, 0:2, stringsAsFactors = FALSE) perms <- all[apply(all, 1, function(x) {length(unique(x)) == 3}),] orders <- as.list(as.data.frame(t(perms))) names(orders)...

Lazy functions evaluation in swift

ios,swift,if-statement,functional-programming,lazy-evaluation

Do not know if this is what you want,you can use function as a type func foo() { println("this is foo") } func bar() { println("this is bar") } func maybeFooOrBar(isFoo: Bool) { let myFoo = foo let myBar = bar let result = isFoo ? myFoo : myBar result()...

Convert loop to Maybe monad

c#,functional-programming,maybe

the answer to your comment/question is: you don't - yeah you could try it using recursive calls but this might fail horrible in C# and you are way better of with the while from x in X is just the monadic - bind (it get's translated into the SelectMany functions)...

returning functions in R - when does the binding occur?

r,function,functional-programming,lazy-evaluation

Here's a solution with a for loop, using R 3.1: > makeadd=function(i){force(i);function(x){x+i}} > for (i in 1:3) { function.list[[i]] = makeadd(i)} > rm(i) # not necessary but causes errors if we're actually using that `i` > function.list[[1]](1) [1] 2 > function.list[[2]](1) [1] 3 The makeadd function creates the adding function...

F# pass by reference

f#,functional-programming,pass-by-reference,out,ref

Your question has a number of parts which I will try to answer: which suggests using a reference cell Yes, Reference Cells (or ref cells) are the idiomatic way to pass mutable data into a function I suppose this means there is no analog to the out keyword in C#...

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

javascript,functional-programming,underscore.js,reduce

Here is the shortest version I could come up with. _.reduce = function(list, iteratee, memo){ var memoUndefined = arguments.length < 3; _.each(list, function(elem, index, list){ if(memoUndefined) { memoUndefined = false; memo = elem; } else memo = iteratee(memo, elem, index, list); }); return memo; }; ...

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

java,lambda,functional-programming,java-8

The simplest solution is to use a stream of Pairs: Stream.iterate(new long[]{ 1, 1 }, p->new long[]{ p[1], p[0]+p[1] }) .limit(92).forEach(p->System.out.println(p[0])); Due to the lack of a standard pair type, it uses a two-element array. Further, I use .limit(92) as we can’t evaluate more elements using long values. But it’s...

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

scala,functional-programming

If you wanted to chain a bunch of these if/then conditions together to modify a string you could consider adding an implicit class to handle the if/then evaluations like so: object UrlPimping{ implicit class PimpedUrl(val url:String) extends AnyVal{ def changeIf(condition:String => Boolean)(f:String => String):String = { if (condition(url)) f(url) else...

Apply a list of parameters to a curried function

functional-programming,sml,currying

The root of the problem is that for this to work, the type of the folded function would have to change as it's folded through the list, and this (hopefully obviously) isn't possible. The "circularity" in (fn (p, f') => f' p) comes from the fact that the type of...

Creating a filterable list with RxJS

javascript,functional-programming,reactive-programming,rxjs,reactive-extensions-js

You'll need to wrap the from(list) as it will need to restart the list observable again every time the filter is changed. Since that could happen a lot, you'll also probably want to prevent filtering when the filter is too short, or if there is another key stroke within a...

Order items based on an other field MySQL

php,mysql,functional-programming

While preparing arguments for WP_Query, you can additionally give field name for sort order.I have modified your $args, its should look like below: $args = array( 'posts_per_page' => "$cs_node->cs_album_per_page", 'paged' => $_GET['page_id_all'], 'post_type' => 'albums', 'post_status' => 'publish', 'orderby' => 'modified' 'order' => 'DESC', ); Notice here that I have...

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

javascript,arrays,object,functional-programming,reduce

The ECMAScript ES5 specification specifically says that the order of properties is not guaranteed for a for/in loop. From section 12.6.4 in the ES5 specification: The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. Though, in most...

Generating Custom Object from ArrayList in C# at runtime

c#,asp.net,.net,dynamic,functional-programming

Ok guys I figured out how to do that and just in case someone who would face this problem here is the solution : you have to tokenize each line using dot(.) and pointer to keep track of the index, you should use pointer with ref keyword in order to...

functional way to accumulate pairs in java8

java,functional-programming,java-8,java-stream

You can move the map steps inside the flatMap: return Arrays.stream(names) .<Person>flatMap( name -> getTokensForPerson(name).stream() .filter(Token::isValid) .map(token -> new Person(name, token))) .collect(Collectors.toList()); This way you can access name variable as well. StreamEx-based solution is shorter, though it requires third-party library: return StreamEx.of(names) .cross(name -> getTokensForPerson(name).stream()) // Here we have the...

Computing a term of a list depending on all previous terms

haskell,recursion,functional-programming,lazy-evaluation,formal-methods

Statutory Calculus Warning. The basic answer to this question involves specialising a standard recursion scheme. But I got a bit carried away pulling at the thread of it. Things take a more abstract turn as I seek to apply the same method to structures other than lists. I end up...

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

javascript,functional-programming

here I am assume the context is window which is global context function set(variablename,value){ window[variablename] = value; } hope this helps you....

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

functional-programming,ocaml

"Function definition" means a literan fun x -> construct. Functional languages consider partial function applications like factor >>= fun l -> ... redexes, not literal values, which means a strict language has to evaluate them immediately when they appear on the RHS of a simple variable binding, like term =...

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

list,pointers,haskell,recursion,functional-programming

That's pretty much what the recursive solution does. It's the copying of a which takes O(n) (where n is the length of a. The length of b doesn't affect the complexity). There is really no "trick" to copy a list of n elements in O(1) time....

Functional way of programming in Java 1.7 [closed]

java,functional-programming

Simple answer: no. Java is an object-oriented programming language, and while Java 8 and third party libraries break up some of the ceremony, at its core you're still dealing with classes. The functional design patterns you're attempting to apply won't work in this language (or if they do it'd be...

Determine the arity of a function handle and currying

matlab,functional-programming,currying,arity

Are you looking for nargin? For example, >> nargin('genvarname') ans = 2 i.e. the function genvarname has an arity of 2...

A little confusion with the sorted function in Haskell

haskell,recursion,functional-programming

If a function pairs :: [a] -> [(a, a)] is defined somewhere, the expression [x <= y | (x,y) <- pairs xs] is a list of a booleans (that is, its type is [Bool]). and is a function whose type is [Bool] -> Bool: It takes a list of booleans...

Idiomatic list construction

list,haskell,functional-programming,idiomatic

The multiple call to addPoints could be replaced by a fold. As suggested in a comment, reversing your addPoint function would make things easier: addPoint' :: Point -> Polyline -> Polyline addPoint' p line = p:line So then your constructLine function could build a temporary list of the points to...

Lazy concat in Immutable.js?

javascript,functional-programming,immutable.js

A lazy breadth-first traversal can be achieved with the Iterable API for Immutable.js: var Immutable = require('immutable'), Iterable = Immutable.Iterable, Seq = Immutable.Seq; var tree = { value: 'foo', children: [ { value: 'bar', children: [ { value: 'bar1', children: [ { value: 'bar1_a'}, { value: 'bar1_b'} ] }, {...

Java stream of optionals to optional stream

java,functional-programming

Well, the tricky thing here is that if you're just given a Stream, you can only use it once. To be stateless and avoid redundant copying, one way is to just catch NoSuchElementException: static <T> Optional<Stream<T>> invert(Stream<Optional<T>> stream) { try { return Optional.of( stream.map(Optional::get) .collect(Collectors.toList()) .stream()); } catch (NoSuchElementException e)...

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

javascript,angularjs,functional-programming

window.angular is the global angularjs variable which is created once angularjs has been fully loaded from a script tag. The code fragment you have pasted ensures that it is executed after the population of this variable. One reason it might be written in that verbose way is simply its auto-generated...

Mapping a vector of one type to another using lambda

c++,c++11,lambda,functional-programming

You said it yourself, this map is not generic enough. std::transform on the other hand is, at the cost of more verbose interface. Another reason is that map, unlike std::transform forces new allocation, which is not always desirable.

Functional way of finding inverse ranges

javascript,regex,functional-programming,templating

Would it be possible to get all of the ranges in one pass? Yes - as you can use a regex with a capturing group to split your input string: var tag = /(\{\{.+?\}\})/; var parts = str.split(tag); and then you can directly map those to your functions: var...

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

javascript,functional-programming,underscore.js,lodash

transformed = _(original).map(function (c) { var coordinates = wgs2gcj(c.latitude, c.longitude); return { lat: coordinates.lat lng: coordinates.lng } }); ...

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

javascript,functional-programming,find,each

This has to do with how return works. Let's look at your code: var find = function(list, predicate) { // you pass list and an anonymous callback to `each` each(list, function (elem) { // if this condition is true if (predicate(elem)) { // return elem return elem; } }); }...

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

c#,functional-programming,deedle

GetColumn returns Series. You just need to get series values and convert them to array. Something like that should work: var arr = values.Values.ToArray(); or var arr = values.GetAllValues().ToArray(); ...

Accessing call stack depth in Scheme

functional-programming,scheme,tail-recursion,callstack

Racket allows you to store values in the call stack. You can use this to keep track of the depth. Here is how I would do it: #lang racket ;;; This module holds the tools for keeping track of ;;; the current depth. (module depth racket (provide (rename-out [depth-app #%app])...

Why prefer Typeclass over Inheritance?

scala,inheritance,functional-programming,typeclass

When using inheritance to achieve ad-hoc polymorphism we may need to heavily pollute the interface of our value objects. Assume we want to implement a Real and a Complex number. Without any functionality, this is as simple as writing case class Real(value: Double) case class Complex(real: Double, imaginary: Double) Now...

What is monad analog in Java?

java,scala,functional-programming

There are two problems with representing monads in Java: flatMap needs to operate on a function that returns the (same) specific monad, and Java's type system cannot express that. unit is kind of a static method in Java terms, because it creates a monad instance from a generic value. Java...

Purity, Referential Transparency and State Monad

scala,functional-programming

I guess you could say that your update itself is pure, in the sense that it only represents some mutation, but as soon as you run it all bets are off: scala> val xs = List(1.0, 2.0, 3.0).to[ArraySeq] xs: scala.collection.mutable.ArraySeq[Double] = ArraySeq(1.0, 2.0, 3.0) scala> update(0, 10).eval(xs) res0: scalaz.Id.Id[Unit] =...

Evaluate a list of functions in Clojure

clojure,functional-programming,clojurescript

(map #(% arg) function-list) Should do the job?...

Create array using _.each

javascript,arrays,functional-programming,underscore.js,each

The functional-programming tag on the question is the clue. :-) In functional programming, usually loops are written as recursion. So how can we use recursion to build an array using _.each? By making the callback call it: var array = _.each([1], function cb(e, i, a) { if (a.length < 1000)...

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

Note that the most circles with radius R contain less than πR² integer points within the boundary, so usually that map doesn't exist. Reference: Gauss circle problem And I suspect that even for good R values there is no simple formula, only iterative aprroach (look at (1) formula in the...

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

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

Having trouble stepping through function that reduces an array of functions

javascript,functional-programming,reduce,higher-order-functions

It looks like you're trying to create a composition function that takes an array of functions to apply to an input, num Let's first cover a couple syntax errors. First you're missing the function keyword // your code comboFunc(num, functionsArr) { // should be function comboFunc(num, functionsArr) { Next, you've...

Swift: Avoid imperative For Loop

swift,ios8,functional-programming

You need both filter() and map() : let mapNames = valueMaps.filter( {$0.name != nil }).map( { $0.name! }) let mapLocations = valueMaps.filter( {$0.location != nil }).map( { $0.location! }) The filter takes a predicate as an argument (which specifies which elements should be included in the result), and the map...

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

functional-programming,java-8,java-stream

All you need is return aSet.stream().anyMatch(b::aMethodReturningBoolean); which is much more readable....

for vs map in functional programming

scala,functional-programming

The answer is quite simple actually. Whenever you use a loop over a collection it has a semantic purpose. Either you want to iterate the items of the collection and print them. Or you want to transform the type of the elements to another type (map). Or you want to...

Elm: understanding foldp and mouse-clicks

functional-programming,elm

You need it because foldp expects a function with two inputs. In this case, the first input is just ignored by your lambda, but the foldp implementation still puts something in there. Mouse.clicks always puts a sort of do-nothing value called Unit in there. Some signals have a value associated...

Lodash equals function

javascript,functional-programming,underscore.js,lodash

Not sure if I fully understand your question, but here's my best guess at what you're after. function equals(val) { return _.ary(_.partial(_.isEqual, val), 1); } _.findKey(keys, equals(2)); // → 'b' _.omit(keys, equals(2)); // { a: 1, c:1 } Here, equals() will return a callback function. It uses ary() to make...

How to get only specific elements of list in racket

functional-programming,scheme,racket

The "normal" way of getting specific element based on their values is to use filter with a suitable predicate. Something along these lines: (define (may? str) (string=? "may" (substring str 0 3))) (define (only-may ls) (filter (lambda (x) (may? (car x))) ls)) ...

First word of binary string erlang

functional-programming,erlang,pattern-matching

Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces): first_word_bin(Bin) -> first_word_bin(ltrim(Bin), <<>>). first_word_bin(<<>>, Acc) -> Acc; first_word_bin(<<$\s, _/binary>>, Acc) -> Acc; first_word_bin(<<X, Bin/binary>>, Acc) -> first_word_bin(Bin, <<Acc/binary, X>>). ltrim(<<$\s, Bin/binary>>) -> ltrim(Bin); ltrim(Bin) -> Bin. ...

Spray routing filter path parameter

scala,functional-programming,akka,spray

My guess is that in your non-working code, length is still an Int, and hence does not match with either Some or None. If you wanted to translate your if-else code to a match-statement, I'd suggest something similar to the following code, which matches for positive Int values: List(10, -1,...

Grouping a range of integers to the answer of a function

java,functional-programming,java-8,java-stream

Well, since I described what I'd do, and there's been a bit of discussion about it, I figured I should write down what I was describing: class IntPair { final int input, result; IntPair(int i, int r) { input = i; result = r; } } Map<Integer, List<Integer>> output =...

Properly implement F# Unit in C#

c#,f#,functional-programming

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way). However, you can actually find the implementation of F# unit in the core library:...

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

scope,functional-programming,lazy-evaluation

This is, of course, doable in a functional, declarative language like haskell. Either with let bindings or where keyword. These are just chained together in one expression. --local variables with 'where' f :: Int -> Int f x = z where z = y*2 y = x*x --local variables with...

OO way or functional way of string comparison conditionals in php

php,oop,functional-programming

What you are searching for a ways of abstraction. In this example you are repeating yourself in case analysis and this might be the best approach if the "do something" is very different and not consistent. $map = [ 'success' => function () { return 1; }, 'foo' => function...

Elm List type mismatch

list,functional-programming,elm

Yes, I'm afraid both of those are old(er) material (than 0.15). Elm 0.15 uses core 2.0.1, in which (as the version suggests) there are breaking changes. The one you're running into is that head and tail now return a Nothing instead of crashing on empty lists. When the list isn't...

Hook into GHC runtime system

haskell,functional-programming,runtime,transactional-memory

(# s2#, TVar tvar# #) is an unboxed tuple. The name stg_newTVarzh is built from: The stg_ prefix, which is common to the whole GHC runtime, and stands for the spineless-tagless G-machine, an abstract machine to evaluate functional languages; newTVar which is the first part of newTVar#; the final zh,...

Functional way of doing a loop of operations on an array

java,scala,functional-programming

There are lots of useful constructor methods in the Array companion object, for example, for your situation here, you can use tabulate: val nvars: Int = 10 val vars = Array.tabulate(nvars){ someFunction } // calls someFunction on the values 0 to nvars-1, and uses this to construct the array vars...

Sum of Fibonacci term using Functional Swift

swift,functional-programming

There is a filter() function which takes a sequence as an argument: func filter<S : SequenceType>(source: S, includeElement: (S.Generator.Element) -> Bool) -> [S.Generator.Element] but since the return value is an array, this is not suited if you want to work with an "infinite" sequence. But with lazy(FibonacciSequence()).filter ( { $0...

Idiomatic exception handling for socket connection

scala,sockets,error-handling,functional-programming,try-with-resources

---EDIT upon question clarification--- To use automatic resource management in a functional style in scala, the easiest way would be to use scala-arm then you can write import resource._ def hostAvailabilityCheck():Boolean= { managed(new Socket(SERVER_ADDRESS, TCP_SERVER_PORT)).map(_=>true).opt.isDefined } If you really, really want to use scala.util.control.Exception you could write : import scala.util.control.Exception._...

in clojure, function argument type mismatch

clojure,functional-programming,lisp

You are misunderstanding the format of a function definition. In your function, the single argument 'colors' is untyped and can be anything. The square brackets are used to denote the beginning and end of the arguments list (i.e. the symbols for the arguments are wrapped in a vector to distinguish...

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

ruby,hash,functional-programming

Yes, it would be a better idea. Consider situation when this hash is being used by multiple instances of different classes. When one of this instances modifies hash, change has impact on the rest. Later it is very hard to debug why something does not work. def without_empty_stories(content) content.inject({}) do...

Why would my find method return undefined?

javascript,functional-programming,find,each

Your return is only returning from the inner (nested) function and your find function is indeed not returning anything, hence the undefined. Try this instead: var find = function(list, predicate) { // Functional style var ret; _.each(list, function(elem){ if (!ret && predicate(elem)) { return ret = elem; } }); return...

Kind Classification of Types

haskell,functional-programming

Kinds are curried just like types. The type of (,) (the value constructor) is a -> b -> (a, b). The type of (,) () is b -> ((), b). The type of (,) () () is ((), ()). Kinds work exactly the same way. The kind of (,) (the...

Turn object into array, add object as new element

javascript,functional-programming,underscore.js,lodash

var newItems = _.map(items, function(item, key){ item.name = key; return item; }); console.log(newItems); ...

Remove item from array using foreach - JavaScript [duplicate]

javascript,functional-programming

I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it...

Apply successive filters to an array in Ruby

ruby,functional-programming

Ok, spoiler, I figured out one solution. Since I could not find this exact problem anywhere I decided to post it here: def filter(array_of_numbers, filters) filters.inject(array_of_numbers) do |remaining_numbers, filter| send(filter, remaining_numbers) end end So, if you had some filtering methods: private def filter_odd(numbers) numbers.select(&:odd?) end def filter_multiple_five(numbers) numbers.select { |number|...

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

How does one develop an intuition to think about a solution to problems of this type? The solution is very clever and quite specific to the problem, but it is also an example of a more general problem-solving strategy called divide and conquer. Instead of attacking the problem in...

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

scala,functional-programming,software-engineering,currying

Imagine a function with multiple parameters add(a,b) = a + b. This function adds two numbers. Now imagine, in some context you need a function that takes just one parameter and you'd like to have a function that adds 5. That function could look like this: adds5(x) = 5 +...

Easier way to apply multiple arguments in Haskell

haskell,functional-programming,composition,functor,applicative

The Applicative class has the <*> operator (usually pronounced "ap", and is equivalent to Control.Monad.ap for most Monads), which combined with the <$> operator (itself just an infix alias for fmap) lets you write code like -- f :: a -> b -> c -- fa :: Applicative f =>...

Functional Breadth First Search

python,haskell,functional-programming,ocaml,sml

One option is to use inductive graphs, which are a functional way of representing and working with arbitrary graph structures. They are provided by Haskell's fgl library and described in "Inductive Graphs and Funtional Graph Algorithms" by Martin Erwig. For a gentler introduction (with illustrations!), see my blog post Generating...

Scala wrong forward reference

scala,functional-programming

You have 2 problems in this code: Not explicitly specifying that the empty and cons methods are located in the companion object Stream To fix this you need to either import Stream._ into your class: sealed trait Stream[+A] { import Stream._ def take(n: Int): Stream[A] = this match { case...

Questions about Vars Clojure

clojure,functional-programming

Assuming that by variable you mean a refer to a mutable storage location, I guess the main difference(depending against which language you compare) is that if you dynamically rebind the var in Clojure is on a per-thread basis. But the long answer is that you don't usually use a var...

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

haskell,functional-programming,monads,do-notation

Well, you've stumbled upon a kind of weird monad. The monad in question is the Monad ((->) r). Now, what does that mean? Well, it's the monad of functions of the form r -> *. I.e., of functions that take the same type of input. You asked what the type...

Java 8 streaming API using with Map

lambda,functional-programming,java-8,java-stream

This looks like somebody let an IDE automagically convert imperative code to streams. I think retErrors.remove(e) is there to leave retErrors empty if any translators matched toFind. This is my best guess of the code's original intent: List<Error> errors = translate.keySet().stream() .filter(toFind::contains) .map(translate::get) .flatMap(translator -> exc.getErrors().stream().map(translator)) .collect(toList()); List<Error> retErrors =...

Is memoizing possible without side effects

f#,functional-programming,memoization,side-effects

To restate what was mentioned in the comments, you can extract memoization into a higher order function that would return a memoized version of the function passed in as an argument: let memoize f = let dict = new System.Collections.Generic.Dictionary<_,_>() fun x -> match dict.TryGetValue(n) with | true, v ->...

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

javascript,functional-programming

This concept comes from lovely Maths. It is called function composition. f(x) = y g(y) = z g(f(x)) = z (g•f)(x) = z That last line is read "g of f of x equals z". What's great about composed functions is the elimination of points. Notice in g(f(x)) = z...

Trial division for primes with immutable collections in Scala

algorithm,scala,data-structures,functional-programming

According to http://docs.scala-lang.org/overviews/collections/performance-characteristics.html Vectors have an amortised constant cost for appending, prepending and seeking. Indeed, using vectors instead of lists in your solution is much faster def primes(n: Int) = { @tailrec def divisibleByAny(x: Int, list: Vector[Int]): Boolean = { if (list.isEmpty) false else { val (h +: t) =...

F# Observable - Converting an event stream to a list

f#,functional-programming,reactive-programming,observable

Events are all about side-effects, so it's limited how much sense it makes to try to be all Functional about it. (Yes: you can build Reactive systems where immutable event data flows through a system, being filtered and aggregated along the way, but at the source, that an event is...

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

haskell,functional-programming

I'm mostly curious how to solve this problem in Haskell without bit twiddling: Interview question: f(f(n)) == -n That's actually quite easy to solve: when :: (a -> Bool) -> (a -> a) -> a -> a when p f x = if p x then f x else...

How to implement this simple algorithm elegantly in Scala

list,scala,functional-programming

Reversing the list and then using foldLeft. def increasingSubsequences(list: List[Int]) = list.reverse.foldLeft(List[List[Int]]()) { case (a :: as, b) if b < a.head => (b :: a) :: as // same subsequence case (as, b) => List(b) :: as // new subsequence } ...

How are point-free functions actually “functions”?

haskell,functional-programming,pointfree

Conal's blog post boils down to saying "non-functions are not functions", e.g. False is not a function. This is pretty obvious; if you consider all possible values and remove the ones which have a function type, then those that remain are... not functions. That has absolutely nothing to do with...

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

scala,haskell,functional-programming

Apart from using scalaz you could also define one yourself: implicit class ListToMapWith[K, V](list: List[(K, V)]) { def toMapWith(op: (V, V) => V) = list groupBy (_._1) mapValues (_ map (_._2) reduce op) } Here is a usage example: scala> val testList = List((5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")) scala> testList...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java

I think, your case can be accomplished with a combination of merge, filter and take: List<Observable<HotelInfo>> hotels = new ArrayList<>(); for (URL u : urls) { Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u); hotels.add(hotelInfo); } Observable.merge(hotels) .filter(h -> h.vacancy > 0) .take(1) .subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace); ...

Declaring a Ruby lambda with a yield

ruby,lambda,functional-programming

You cannot yield from a lambda directly to a nonexplicit block passed to it as you are doing now (See comments below for source provided by @cremno showing that yield may only be used in method and singleton class definitions) Source Extraction: if ((type != ISEQ_TYPE_METHOD && type != ISEQ_TYPE_CLASS)...