Questions tagged [functional-programming]

Functional programming is a programming paradigm based upon building abstractions using functions, avoiding side effects and change of state. Pure functional programming is thread-safe.

Filter by
Sorted by
Tagged with
1
vote
1answer
28 views

Why doesn't this test work for my map function as written?

I am asked to create a test for my map function below. static <U,V> List<V> map(Iterable<U> l, Function<U,V> f) { List<V> hashes = new ArrayList<>(); for(...
1
vote
1answer
32 views

Cats' Monoid instance throws exception when merging Maps of Arrays

I defined a Monoid instance for Map[Int, Array[Int]] and tried to use it to merge a list of such maps: import cats.Monoid import cats.implicits._ implicit val m: Monoid[Map[Int, Array[Int]]] = ...
2
votes
1answer
49 views

How many head-choppings does Hercules have to perform to kill the Hydra in Haskell?

I am pretty new to Haskell. I have been struggling with for very long and have tried everything I can think of. What I want the function to do is to check the first nonzero element, decrement it by 1, ...
0
votes
0answers
55 views

Can I have C# with functional style and dependency injection?

I want to have some classes which provide a method with (a) the same name but different implementations; (b) I also want the methods to be used in the functional/linq-extension style in C#; (c) I ...
0
votes
0answers
15 views

Speeding up nested evaluations (Isabelle/HOL)

I have an Isabelle/HOL definition looks like definition "f1 args = filter g (f0 args)", where f0 returns a list (this detail is not particularly important, though). Now, if I try to compute value ...
2
votes
2answers
60 views

Problems with Java Generics while building a monad

I'm playing around Java code in order to create a functional style monad, but I get struck while using generics and the Java compiler gives me a compilation error if I don't cast my object (though ...
0
votes
0answers
30 views

Can partial application work with async functions? [duplicate]

I try to use partial application on an async function, but it always returns a promise. Is there any way to make it work? const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));...
1
vote
1answer
79 views

How would I get the minVal without a loop and using only foldLeft?

So, I have gotten a bit of an understanding of functional programming but for this I cannot use a loop and instead have to use the foldLeft or foldRight function that I wrote, on order to get the ...
0
votes
1answer
19 views

Finding middle element in a Standard ML list

I am trying to find the middle element of a list in SML without using any pre implemented functions of the form List.whatever. I can use a function that takes 2 of the same lists, recursively calls ...
2
votes
1answer
90 views

Is Fortran a purely functional language?

I understand that some languages combine elements for many different paradigms in programming. I'm told that Fortran is an example of a Functional language, however I'm just a little confused as to ...
2
votes
1answer
21 views

How to write a function that handles a Union type in Dhall

I'm trying to wrap my head around how programming works in Dhall. Consider the following union type: let Object = < NoId | WithId : Text > I want to write a function extractId that returns an ...
-1
votes
1answer
69 views

Matrix of string, with unique columns and rows, latin square

i'm trying to write a function that for n gives matrix n*n with unique rows and columns (latin square). I got function that gives my list of strings "1" .. "2" .. "n" numSymbol:: Int -> [String] ...
5
votes
3answers
61 views

Space complexity of streams in Scheme

I am reading Structure and Interpretation of Computer Programs (SICP) and would like to make sure that my thinking is correct. Consider the following simple stream using the recursive definition: (...
0
votes
2answers
38 views

How to elegantly “min” and then perform an operation with the reference in python

Suppose you have two lists nums1 and nums2, and you want to check which of the two lists first elements is smaller, remove it and then move that into an accumulator list which you return. You might ...
-2
votes
2answers
175 views

how to parse json with field of optional and variant type in Haskell?

How I can parse the input json inside this file ? https://github.com/smogon/pokemon-showdown/blob/master/data/moves.js For the secondary and flags properties? They are optional and contains variant ...
0
votes
5answers
95 views

Generate a custom pattern number sequence in one go

I'd like to generate the following number sequence in one go using a functional initialization construct: Array(0, 0, 0, 0, 3, 3, 6, 6, 9, 9, ..., n*3, n*3) One way is to do: Array.fill[Int](2)(0) +...
3
votes
1answer
65 views
+100

Saving to database in stream pipeline

As per the documentation on Oracle's website: Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the ...
1
vote
2answers
33 views

How to pass the weights of previous layers as input to a call function,of a custum layer, in a functional Keras Model?

For the call method of my custom layer I need the weights of some precedent layers, but I don't need to modify them only access to their value. I have the value as suggest in How do I get the weights ...
1
vote
3answers
94 views

Monads and liftM

I'm having a problem using liftM. For (+) it works fine, the function madd a b = liftM2 (+) a bgives me the expected result Just 5 `madd` Just 7 = Just 12 but now trying it with (/) it gives me ...
1
vote
1answer
47 views

How to send a generic object in place of a Type variable (or Any) in Scala

I'm solving problem 20 on this page - http://aperiodic.net/phil/scala/s-99/ This is the code I have written import scala.annotation.tailrec import scala.collection.immutable.Nil import scala....
1
vote
2answers
72 views

what is the difference between filtering on accumulator/current in reduce method

When chaining the Array.prototype.reduce with Array.prototype.filter what is the difference (conceptually and under the hood) when filtering on the current value instead of the accumulator value? // ...
1
vote
2answers
35 views

using my own reduce function to check array intersection

I wanted to create a small application that could check arrays for intersecting values and reduce those arrays in a new one with only intersecting numbers. I was able to accomplish this using built in ...
1
vote
0answers
43 views

Is noop a pure function? [duplicate]

In JavaScript, we can express a simple noop function like so (It's the same in Lodash): const noop = () => {}; It might be a frivolous distinction, but does it count as a pure function? My ...
1
vote
1answer
60 views

Can fix be tail recursive and thus expressed as a simple loop?

I can't figure out how to express fix as a tail recursive algorithm. Or is it already tail recursive? I am probably overthinking it... const fix = f => x => f(fix(f)) (x); // redundant eta ...
0
votes
0answers
29 views

How to pass a list of instance methods to be executed in another method using Java 8 [closed]

Suppose I have the following methods: Defined in MyClass1: String method1(String); Defined in MyClass2: String method2(java.util.Date); Defined in MyClass3: String method3(String, BigDecimal); Is it ...
0
votes
0answers
36 views

Why using goto is regarded as bad practice, but call/cc isn't?

I am currently learning the concept of continuations. I am struggling with understanding why direct control flow manipulation by e.g. goto command is a bad practice, but doing so using call/cc is just ...
1
vote
2answers
36 views

Populating a list with results from queue within a while loop in scala

I am trying to write a while loop in a functional way in scala. What I want to do is populate a list with the messages from a queue (Kafka in this case but doesn't really matter). I'm doing this for ...
0
votes
1answer
29 views

Reduce Array of Objects with Dynamic Keys

This seems like it should be pretty simple but my searching hasn't turned anything up. I have an array of objects that looks like this: [{"A":4,"B":2},{"A":2,"B":1},{"A":3,"B":1},{"A":2,"B":1,"C":1}]...
0
votes
1answer
26 views

A iterator/generator can be considered a stream?

I'm reading the SICP and ended up in the part of streams. Would a python iterator/generator can be considered a stream? This iterator for example: class MyNumbers: def __iter__(self): self.a ...
0
votes
0answers
51 views

How to perform a `Collectors.toList()` correspondingly in scala

I have the following class and method used in the code below with ids being a Set[String]: case class PAV () def aggregate(pId: String, iId: Option[String], count: Int): PAV I have tried the ...
0
votes
1answer
52 views

Typing curried function in Python

There is such a function for currying. The problem is that I don’t know how to make this function return a decorated function with the correct types. Help, I have not found a solution anywhere. ...
0
votes
1answer
44 views

Kotlin: Idiomatic & Declarative way to find count of a loop without mutation

How to count no.of times a loop has run with a condition, for example: var count = 0 while (stk.isNotEmpty()) { stack.pop() count++ } But this involves a temporary counter and mutation. Is there ...
-1
votes
1answer
48 views

Why doesn't JS complier recognize this call to Array.prototype.filter

Hello thank you for reading this and taking the time to answer my question. I am trying to figure out why my call to .prototype.filter is giving me a TypeError: curr.filter is not a function. const ...
1
vote
4answers
54 views

Function<? super T, ? extends Comparable> does not accept objects of super types of T?

I am dealing with the following puzzle. class Product {} static class Fruit extends Product implements Comparable<Fruit> {} class Apple extends Fruit {} Function<? super Fruit, ? extends ...
3
votes
1answer
71 views

Common Lisp - Pattern Matching

I'm trying to write a function which compare two lists in Common Lisp. The sign ’&’ indicates any sequence of elements and the sign ’$’ indicates any single element. (defun match (filter data) ...
1
vote
2answers
45 views

reduce list of functions with keyword argument on dictionary in python

:) I want to build a very tiny functional pipeline in my code to reduce a bunch of functions on a single dictionary. Every function does 1 thing, but on different keys, here's a simplified example: ...
1
vote
3answers
112 views

How to return a function resulted from alternate combining two lists of functions in Haskell programming?

In my Haskell course assignment, I want to cope a challenge which is essentially to catch on how to process lists of functions. The input consists of two such lists, lets say first of them is given as ...
-2
votes
1answer
16 views

How to use defined function in functional API keras

I'm super confusing with lambda layer during functional API please tell me which is correct For example def magic(x): x2=x+x return x2 D = Input((n,)) E = Lambda(magic)(D) d = Model(~~~~) ...
0
votes
1answer
30 views

ArrowKt Try alternative for eager execution

ArrowKt has deprecated Try since it promotes eager execution of effects and it recommends to use suspend constructors. But how should I handle following case where I do want eager execution on ...
0
votes
3answers
51 views

How do I get a list of items from a subset of a list, based on the items in another list in Java?

I've got a List<String> which represents the ID's (can be duplicate), of items from another list, which is a List<Cheat>, where each Cheat has a String ID and a List<Integer> RNG. ...
0
votes
4answers
68 views

Turn 1d array into 2d array in swift [duplicate]

If I have a one-dimensional array: oneDimArray = [1,2,3,4,5,6,7,8,9] and I already have a 3X3 two-dimensional array with the right amount of slots to fit the numbers twoDimArray = [[0,0,0], [0,0,0]...
1
vote
1answer
62 views

Can recursively variadic functions be typed in Typescript?

I have the following generic function I can derive various useful variadic functions from: const variadic = f => { const go = args => Object.defineProperty( arg => go(args....
0
votes
0answers
28 views

Char -> String without quotes [duplicate]

I have problem with making list of chars , but casted to string. I tried write function: charSymbol:: Int -> [String] charSymbol n = map show (take n ['a'..'z']) I wanted to have list like ["a", ...
0
votes
0answers
42 views

Use Either with Future

I want to use dartz functional style and do something like this: Either<Failure, Response> result = await remoteDataSource.request() // Future<Response> request(); .then((response) =&...
0
votes
1answer
33 views

What is a “dimension snapshot” in a functional data engineering approach to deal with slowly changing dimensions?

As mentioned by Maxime Beauchemin in his popular post Functional Data Engineering — a modern paradigm for batch data processing, Maxime recommends dealing with slowly changing dimensions by taking ...
1
vote
1answer
76 views

In Java why is Function.identity() a static method instead of something else?

Java 8 added functional programming constructs, including the Function class and its associated identity() method. Here's the current structure of this method: // Current implementation of this ...
6
votes
1answer
72 views

Is Eta interoprable with Java and/or Kotlin yet?

I've been learning Haskell, but during my day job I am writing Kotlin/Java. I've come across Eta (https://eta-lang.org/), a Haskell dialect that compiles to Java byte code and runs on the JVM. On ...
0
votes
0answers
9 views

Replace elements in a matrix with respective values from a table under a condition

I need some help on replacing some elements on a matrix. One file is a binary matrix, with species' names on columns and sites on rows, and '1' or '0' numbers for presence or absence. I need to ...
8
votes
0answers
141 views

Semantics for de Bruijn levels [migrated]

There is an exceptionally simple way to embed simply typed lambda calculus with de Bruijn indices in a functional host language (discussed by Carette, Kiselyov & Shan, and by Kiselyov). The ...
2
votes
1answer
56 views

Achieving laziness and memoization

Laziness is a corner stone in the book Purely Functional Data Structures, but it is not clearly described how he obtains it, at least to me. I thought I only needed to write: datatype 'a susp = $ of '...