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.
18,243
questions
0
votes
1
answer
19
views
Name binding in pattern matching in OCaml
What does the name binding with the as- keyword do in this exercise:
https://ocaml.org/problems#17
# let split list n =
let rec aux i acc = function
| [] -> List.rev acc, []
| h :: ...
0
votes
1
answer
44
views
The function 'print' is applied to three arguments [duplicate]
Consider the following code:
import Data.Char
numToReal::Integral a => [a] -> [Double]
numToReal l = map (\x -> fromIntegral x) l
ordList::[Char] -> [Int]
ordList l = map ord l
...
0
votes
0
answers
50
views
Functional programming is confusing. How do i make side effects? [closed]
If pure functions must not have side effects, then how do i do side effect stuff like writing to a file in functional programming? Or we never need to write to files or read from database??? weird :)
0
votes
1
answer
40
views
What is the best way to create an infinite curry function in Javascript to allow for re-using functions partway through?
I've created a curry function in Javascript:
// fn takes two arguments: accumulator, value
function infiniteCurry(fn, startValue) {
return function (n) {
let acc = startValue;
function ...
1
vote
1
answer
52
views
F# Subclasses and Memoization
I am struggling to get memoization to work when the memoized function is an abstract function which is overridden/defined within a subclass rather than the parent class.
When the memoized function is ...
0
votes
1
answer
48
views
haskell compile parse error (possibly incorrect indentation)
i am new to haskell and i am trying to make the following code work:
abc :: fooType
abc = do
let loop c d = do
let q = borrow "a"
d2 = d + q
c2 = c + 1
...
1
vote
0
answers
21
views
Nested Mono in Either
I have a method to register a user:
public Mono<Either<AppError, UserDTO> > registerUser(RegisterUserDTO dto) {
Mono<Either<AppError, Mono<UserDTO> > > result = ...
0
votes
3
answers
64
views
Clojure - map a partition over a sequence
I have two collections of the same size - I have partitioned the first one and would like to apply the same partition to the second one. Is there an elegant way of doing this? I have found the ...
1
vote
1
answer
18
views
LanguageExt - Compiler error using method that returns Task<Either<string, T>> in a Linq query
Having thought I'd got the hang of this, I'm stuck again!
I'm trying to write a method that takes an encrypted string as a parameter. That string contains the serial number and password of a device ...
-1
votes
1
answer
50
views
Why the same function prints different output?
I have defined the following module to implement a matrix type:
module MatrixImplementation: MatrixADT.MatrixInterface =
struct
type 'a matrix = {n: int; m: int; c: 'a array array};;
let ...
0
votes
1
answer
52
views
Making Let binding parsing in Haskell
I want to create parser-like behaviour in Haskell such that I can assign an expression to a variable based on a string. I have difficulties doing so.
If I have types with the following definitions:
...
1
vote
2
answers
36
views
functional programming problems -- map_df & regex
I am trying to combine multiple spreadsheets (about 20) using a functional programming approach. Each spreadsheet contains an individual year of data. They are messy, with columns not named or name of ...
0
votes
1
answer
38
views
How to generalize methods using functional Java
Can we reduce code duplication with these methods with the new java functional paradigm? I tried to pass the function as param. But one has Functional and the other BiFunctional. Unable to make it as ...
0
votes
2
answers
34
views
Scala parsing generic argument of a function
I want to build a function that takes as input a generic function with one argument,
than parse the argument based on type and call the input function:
class PatternMatching {
val a = "test&...
1
vote
1
answer
79
views
How can I create a random 2d array in Haskell?
I am fairly new to Haskell and I'm always confused when it comes to dealing with random values. This time I'm trying to create a 5x5 2d-array in which every cell contains a random value between 4 ...
0
votes
1
answer
37
views
How to buffer a stream in a functional programming?
I'm trying to do realtime audio processing in functional programming (in rust, but this is not the point).
So my idea is to take the inputs samples from a library called cpal (it reads the default ...
-1
votes
3
answers
54
views
What is wrong with this code for creating lists in OCaml?
I am trying to create a program in OCaml [randlist len max], which would generate an int list of length len with integers smaller than max.
I am wondering what is wrong with the following code:
let ...
1
vote
0
answers
42
views
What is this operation called in functional programming?
I just wrote a function with this type in TypeScript. It seems like a useful pattern for use in pipelining, etc. -- it certainly simplified the code I was working on. I would intend to overload this ...
1
vote
1
answer
69
views
Functional programming in C#, how can I convert this imperative method into functional approach?
I'm trying to convert my business logics, and many of my code are like this:
public Result1 Logic1(int a)
{
var b = ComputeByA(a);
var c = ComputeByB(b);
var d = ComputeByC(c);
return new ...
0
votes
1
answer
25
views
Traverse/sequence an Array<Either<E, A>> into Either<Array<E>, Array<A>> in fp-ts
I have a list of entities where even one failed validation would yield an error. However, I'd still like to iterate the whole list and collect all the errors for further logging.
Traverse/sequence ...
0
votes
0
answers
19
views
Lens onto intermediate properties in fp-ts computations
I'd like to improve the code that uses bindTo to add additional computational context.
The problem it introduces is that I have to destructure such context down the computation pipe, which introduces ...
0
votes
0
answers
18
views
Conventional way to save an aggregation over initial data to use in further processing in fp-ts
A common use case that I encounter is the need to pre-calculate some data set for further use in computation, i.e.
const users = [{active: false, id: 'userId1'}, {active: true, id: 'userId2}];
const ...
2
votes
2
answers
36
views
Curry function with the first one as an async function isn't working
I'm trying to curry a function but when the first one is async it throws the error function1(...) is not a function, however if I pass the async function as the last one it works fine.
Can anyone tell ...
1
vote
1
answer
39
views
Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior?
Is it appropriate to use OO-style interfaces and classes when all you really need is function-like behavior (i.e. no need to track or mutate state and the instance exists just to call its only exposed ...
0
votes
0
answers
20
views
What is the need of hooks in react?
I am an angular developer and started learning React. I got to know that there are two ways a React component can be created.
1. component using React.Component
2. Component without React.Component ...
1
vote
1
answer
77
views
F# Memoization Within a Class
I am struggling to make Memoization work in F# when the function I want to Memoize is a member of a class.
The Dictionary appears to be cleared every time - and so nothing is actually memoized, the ...
-2
votes
1
answer
10
views
How to define result type of anonymous function?
I want to use tuples as result types in array.map(..) and I am looking for a way to not define their types upfront as my functions are usually short and result in tuples with only two components.
What ...
1
vote
2
answers
87
views
Functional programming in C#, how can I handle statements like logging, rendering ui, etc?
I read this article : https://docs.microsoft.com/en-us/archive/blogs/ericlippert/foreach-vs-foreach
and the article says:
The first reason is that doing so violates the functional programming ...
1
vote
1
answer
76
views
How to declare the parameter in a JS function to be only string data type?
I have a beginner's exercise in JavaScript and the current code looks like this:
// Task 1: Build a function-based console log message generator
function consoleStyler(color, background, fontSize, txt)...
1
vote
1
answer
52
views
Using the "of " keyword in OCaml
What does the of keyword do in these definition of lazylist and a function using the type?
Is it just a constructor which defines the type of Cons, so that it takes a unit and computes a llist, or is ...
0
votes
1
answer
27
views
when use "Either in fp-ts" for front-end develop?
tldr : I want to know when to use "either" except network I/O.
In my understanding, Either is used when distinguishing success from fail.
So I use "Either" when network request ...
1
vote
1
answer
36
views
Destructuring records in Elm with "as" word
I'm doing the Elm exercises in Exercism again and there's a thing unclear to me so far. How does the "as" destructuring work? In the beginning I didn't understand anything. After read Yang ...
-2
votes
0
answers
14
views
What tools do you use for Code Discoverability? [closed]
How do you get comfortable with a new codebase?
What tools do you use?
Is Static Code Analysis related to Discoverability?
I personally have used class browsers like Pharo's Calypso, Eclipse's Java ...
2
votes
1
answer
44
views
How do I bind a Task<List<Card>> to Either<> with Language-Ext
I have devices (eg mobile phones, payment terminals, etc) that can request a list of cards held in a database. For security, the devices need to authorise themselves, and present their serial number ...
0
votes
2
answers
53
views
Rust: Apply function n times
The problem
I want to create a function (chain) that takes a function f: Fn(i32) -> i32, number n and returns a new function g: Fn(i32) -> i32 that applys f to it's input n times.
For example: ...
0
votes
0
answers
29
views
Find GCD of integer Array in Scala using functional approach [closed]
I have started learning scala, can any one here help me to write a functional approach to GCD of integer Array in Scala, it will help me to understand the Scala's functional programming.
0
votes
1
answer
34
views
requestAnimationFrame loops with timestamps in PureScript
I am trying to pick up PureScript. Something I do a lot in JS is the following:
let start;
function step(timestamp) {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - ...
1
vote
1
answer
45
views
Apply callback to 2 arbitrary length arrays using functional programming in JavaScript
Given that these function declarations exist within scope:
function compose() {
var funcs = arguments;
return function() {
var args, i;
args = arguments;
for (i = funcs.length - 1; ...
0
votes
0
answers
20
views
Divide a set of curves into groups using functional data analysis
I have a dataset containing about 500 curves. In my dataset every row is a curve (which comes from some experimental measurements) and in the columns there are the measurement intervals (I don't think ...
-4
votes
0
answers
65
views
How to create a style variable in functional porgramming in Javascript? [closed]
How do I do this?
Task 1: Build a function-based console log message generator
In this exercise, your task is to code a function named consoleStyler, which accepts four parameters:
color
background
...
2
votes
2
answers
55
views
How to apply Direct function in Stream.map() like in JavaScript
Have a question, when I use a stream map in Java I have to be explicit with the lambda. Suppose I have this mapper function:
public static Integer mapFunction(Integer number){
return number + 3;
}
...
0
votes
1
answer
48
views
Function call not accepting :: operator in argument
I'm supposed to write a recursive functional concatenation function in Scala without using standard list operators.
def myConcat: (List[Any],List[Any]) => List[Any] = {
case (xs,Nil) => xs
...
-1
votes
0
answers
40
views
Understanding why Scala fold has its type restriction- what can go wrong? [duplicate]
I want to write a generic function that can count the number of elements of a List that match a given value. I have tried to implement this using fold:
def countVals[A](v: A, input: List[A]): Int =...
1
vote
3
answers
54
views
What's the purpose of Just in Elm?
So, I have been doing the Elm track on Exercism.org and I just finished the exercise about the Maybe concept, but one thing is not clear to me yet. What is the purpose of the Just in the definition of ...
3
votes
2
answers
156
views
Scala equivalent of `data` declaration in Haskell
I'm trying to write Scala code in a functional style, and want to create a custom type such as the following Haskell definition:
data Day = Mo | Tu | We | Th | Fr | Sa | Su
I know that Scala tends to ...
0
votes
1
answer
42
views
Use cases for List.compare in OCaml
I don't fully understand the type interface of List.comparewhich is:
('a -> 'a -> int) -> 'a list -> 'a list -> int
Are there any other use cases beside those examples:
List.compare (+) ...
0
votes
3
answers
96
views
What's an idiomatic way to traverse and update data structures functionally in Scala?
I'm coming from a Python-heavy background and trying to learn Scala through a basic "Design a Parking Lot" exercise. I have Scala code that looks something like:
class ParkingLot(spaces: Set[...
0
votes
2
answers
76
views
Implementation of Array.length in OCaml
I want to understand how Array.length is implemented. I managed to write it with Array.fold_left:
let length a = Array.fold_left (fun x _ -> x + 1) 0 a
However in the standard library, fold_left ...
0
votes
2
answers
50
views
Comparison in pattern matching in OCaml
I want to write a function set which changes the index i in the 'a array a to the value 'a v and raise an invalid_argument exception if i is bigger then the length-1 of the array.
I know that this can ...
3
votes
2
answers
98
views
How can I find the definition of a Prelude function?
I'm currently trying to find the definition of the words function to help get an idea for a similar function I'm writing. So I was wondering is there somewhere that has all the definitions of the ...