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,976
questions
0
votes
1
answer
54
views
UseCallback(), which variables to add to the dependency array?
UseCallback(), are function paramaters always added ot the dependency array in default? whereas variables used directly wihtin the function's body should only be added if I am sure they would be ...
0
votes
0
answers
45
views
Data dependencies and caching
I have a complex python function which computes a level based on various sub functions and data dependencies.
What are the best ways to control the data dependencies and have reproducible calculations?...
0
votes
1
answer
44
views
what if I want to create a inner function which will access the outer scope variable, but it can't be a closure? is it possible?
I want to understand that if I have use case, which is inner Function needs to access the outer scope variable but it can't be closure(it can't remember the value of a variable even if outer function ...
1
vote
3
answers
79
views
Optimizing Haskell Function to Apply Rules Correctly and Avoid Duplicate Characters
I have an assignment that asks us to implement some functions.
We must implement a function apply :: State -> [Rule] -> State
where State is a String and Rule is data Rule = Rule Char State ...
0
votes
0
answers
36
views
Composability: Iterator vs Lambda
I am having trouble understanding the concept of 'good' functional composability. Assume the following approaches for deleting files with a specific extension:
Using Lambda functions:
def ...
3
votes
1
answer
64
views
Functions that can be deduced by their type signature
I was introduced to this idea informally by this c++ talk Ben Deane “Using Types Effectively"
For example:
template<typename T, typename U>
T f(pair<T, U>);
can be deduced to be ...
0
votes
1
answer
64
views
Is there a better way to infer the transformed record from a readonly record in typescript?
I have a record ROUTES which have can have route name and its properties. Every route must have path and title key and any additional property.
export type TRoute = {
path: string;
title: string;
}...
0
votes
0
answers
40
views
Is there a type-safe functional-relational mapping framework for Python which is compatible with mypy?
Having come from Scala and functional-relational mapping (FRM) using Slick, I was wondering whether there are similar frameworks in Python?
I would like to write database code declaratively using ...
0
votes
1
answer
31
views
Pascal Triangle in OCaml: Get next line as a list
I am trying to get an OCaml function which gives the next line of a Pascal's triangle as a list for example:
(next_line: int -> list -> int list)
let get_next_line [1;1] returns [1;2;1] and so ...
0
votes
0
answers
113
views
Is there a name for `[[[(a, b, ..., z)]]]` -> `([[[a]]], [[[b]]], ..., ([[[z]]]))`?
Is there a name for this operation? (Also is there a name these functions whose type signature can have only one possible/natural "instantiation"?)
How is this function typically implemented?...
-1
votes
0
answers
85
views
I'm writing a C++ program which calculates the number of paths in an Euler Graph, specifically the "Haus vom Nikolaus"
I'm working on a homework assignment for university and have to write a C++ program which calculates all possibilities of paths in an Euler Graph for a certain starting node. I am stuck because my ...
0
votes
0
answers
14
views
Use Ramda to find child index and corresponding parent index
I have 2 implementation which you can see below and I don't see how it can be simplified. Also, maybe I'm missing something about function composition here, I would be glad to get any help.
p.s.: It ...
0
votes
1
answer
36
views
Correct way to check for true value without exiting loop in Kotlin
I'm working on a application in Kotlin that needs to iterate over a range, calling a sub-function for each item. The function then returns a boolean indicating if any of the sub-function calls ...
0
votes
2
answers
66
views
Declaring foldl ( from left) in terms of foldr (from right)
I have foldl:
let rec foldl f lst acc = match lst with
| [] -> acc
| hd::tl -> foldl f lst (f hd acc)
and I have foldr:
let rec foldr f lst acc = match lst with
| [] -> acc
| hd::tl ...
-1
votes
1
answer
45
views
Getting the two minimum values from a list in OCaml
I need to write a function twoMin: int list → int * int using foldl that returns the two smallest values (not elements) of a list. You may assume that the list contains at least two elements with ...
4
votes
1
answer
58
views
Difference between newtypes and type synonyms for polymorphic constrained types
I know that newtypes can be used to avoid leaky abstractions when designing modular Haskell code. It's actually the only discussed difference between using newtypes versus type synonyms that I've ...
-1
votes
1
answer
29
views
Using foldl to get the mean of a list
I am trying to get the mean of a list by using the following helping function:
let rec foldl f l b = match l with
| [] -> b
| x :: l -> foldl f l (f x b);;
let avg l = foldl (fun x acc ->...
0
votes
1
answer
17
views
Does fp-ts offer sequence for object?
R.sequence is endlessly useful. If I have this:
const p0 = {
a: O.some(1),
b: O.some(2),
};
I can do this:
const p0o = R.sequence(O.Applicative)(p);
and get back an O.Option<Record<string,...
1
vote
1
answer
39
views
Trying to get the number of even and odd integers in a list
I am trying to write a recursive function that takes in a list as argument and returns the number of even and odd numbers in tuple (number_of_even, number_of_odd)
let rec countEvenOdd lst e o =
...
1
vote
3
answers
34
views
OCaml list flattening using a recursive function
I am trying to get a recursive function to flatten lists where I am not allowed a helper function. I can only use @. And I'm trying to use "match with"
I tried this way
let rec flatten lst1 =...
0
votes
1
answer
41
views
OCaml higher order functions
Somebody please explain the algorithm in this problem for OCaml.
I have the solution but I do not understand it.
Define iterup: (int * 𝛼 → 𝛼) → int → int → 𝛼 → 𝛼. Iterup takes a function which ...
-3
votes
1
answer
90
views
How do I use lambda to replace for loop and still maintained functional programming? [closed]
this is the original code
def cage_cats(S):
maxtemp = 0
temp = list(set(S))
for i in range(len(temp)-1):
for j in range(len(S)-1):
if temp[i] == S[j]:
...
0
votes
1
answer
84
views
Lack of Finite Element Method implementations in Haskell - Any specific reasons? [closed]
I'm curious to understand why there seems to be a scarcity of Finite Element Method (FEM) implementations in Haskell, or any functional language. Given Haskell's purely functional nature, I expected ...
0
votes
1
answer
36
views
What is the time complexity of this? It uses 3 loops and the innermost loop depends on the outermost?
function fun(N) {
let k = 0;
for(let i = N; i >= 1; i = i/2) {
for (let g = 1; g <= N/i;g = g + 1) {
for (let h =1; h <= i;h = h + 1) {
k = k +...
-2
votes
1
answer
53
views
How can I change this code from imperative programming into functional programming? [closed]
def validate_cats(N, S):
if N%2 == 0:
pass
else:
print("Error : Can only be even number only")
exit()
for i in range(0, N):
x = int(input())
...
0
votes
1
answer
38
views
How to thread, pipe or compose functions in lua?
What to do in lua if I want to pass a value to foo(), pass it's return to bar(), pass it's return to baz() etc?
Exhibit A (pseudocode):
backwards(code(reading(like(not(do(I))))))
Exhibit B (...
1
vote
1
answer
64
views
'Inheriting' Show between different defined data types in Haskell
data Player = User | COM deriving Eq
data Spot = JustA Player | None deriving Eq
instance Show Player where
show User = "X"
show COM = "O"
instance Show Spot ...
0
votes
0
answers
36
views
Currying a lifted function using python toolz
I am
defining a function of 3 variables,
lifting it to a function on list,
then currying that lifted function,
applying the first two arguments lists
Finally applying the last argument
The code is ...
2
votes
2
answers
98
views
How to correctly identify pure functions in functional programming?
Is this function pure or impure?
function greet(name) {
return "Hi I'm " + name;
}
The property of pure function is that it has no side effects and always returns the same output for ...
6
votes
0
answers
384
views
Are there Haskell-like languages where equations allow for arbitrary left-hand sides? [migrated]
In Haskell, you can define algorithms by equations that pattern-match on left-hand side constructors. For example:
data Nat = S Nat | Z
double :: Nat -> Nat
double Z = Z
double (S x) = S (S (...
1
vote
1
answer
135
views
Why is in-place mutation represented with `IO`?
Why are mutable data structures and other mutability represented using IO in functional languages? I'm looking at e.g. Haskell's IORef or Idris' IOArray.
I don't think I mean this as a historical or ...
1
vote
1
answer
74
views
How is fixed point used for overriding nixpkgs packages?
https://nixos.org/guides/nix-pills/nixpkgs-overriding-packages.html says
17.3. Fixed point
...
nix-repl> fix = f: let result = f result; in result
nix-repl> pkgs = self: { a = 3; b = 4; c = ...
3
votes
2
answers
71
views
How can I create a live sub-collection based on a predicate?
Background
I have an interface
public interface ThingRegistry {
public Set<Thing> getAllThings();
public Set<Thing> getAllThingsWithProperty(String property);
}
And an ...
0
votes
1
answer
53
views
compilation error due to type mismatch in generic class
CODE:
public T orElseGet(Supplier<? super T> supplier) {
if (this.isPresent()) {
return this.get();
} else {
return castFromSupplier(supplier);
}
}
private static &...
1
vote
0
answers
35
views
Are these two ways the same for overriding a function?
https://nixos.org/guides/nix-pills/override-design-pattern#id1431 provides a way of overriding a function f:
rec {
makeOverridable = f: origArgs:
let
origRes = f origArgs;
in
...
1
vote
3
answers
157
views
Haskell Depth-First Graph Traversal has Infinite Loop
I have spent some time recently trying to make a depth-first traversal algorithm in Haskell. However, with my one I would like the function to return a 'visited' list, which has every node visited in ...
-4
votes
1
answer
87
views
Haskell function for Tic Tac Toe [closed]
I trust you're all doing well. I'm reaching out with a humble request. I've been working on a series of Haskell exercises I discovered online, and things have been progressing smoothly. However, I've ...
0
votes
2
answers
117
views
Can I compose functions using std::bind*?
I'm playing with functional programming in C++20 and write something like that:
template <class OuterFn, class InnerFn, class... Args>
concept Composable =
std::invocable<OuterFn, std::...
-1
votes
0
answers
77
views
Shortcut for pipe(do async function, TE.mapLeft) in fp-ts?
I am new to fp-ts.
I usually make codes to call async functions return Promise<Either> as below.
pipe(
TE.bind('info1', ({}) =>
pipe(
() => asyncGetInfo1(),
TE.mapLeft(...
2
votes
1
answer
97
views
Approach to handle errors passed up the call chain using Eithers
I'm currently learning more about functional programming and alternative approaches to error handling than what I'm used to (try/catch mainly). And have been looking at the Either monad in various ...
6
votes
3
answers
441
views
How to compose functions through purely using Python's standard library?
Python's standard library is vast, and my intuition tells that there must be a way in it to accomplish this, but I just can't figure it out. This is purely for curiosity and learning purposes:
I have ...
2
votes
2
answers
48
views
How to correctly type a chained functions generator function in Swift?
In Swift in particular (but honestly I would like a good solution in any typed language) I would like to correctly type a function combinator function.
I do have a fair bit of experience with typed ...
0
votes
0
answers
26
views
Tkinter Menu within menu
I have a application written tkinter and created menu within menu to select book categories
The problem is that I can't write category names which have subcategories to button. If there is no ...
1
vote
2
answers
63
views
Lift state monad to focus on part of a record
With the following code snippet:
data Circle = Circle
{ center :: Point
, radius :: Double
}
data Point = Point (Double, Double)
someFuncOverPoint :: State Point ...
0
votes
1
answer
72
views
OCaml Addable Numbers
I'm learning OCaml, from a little bit of Haskell that I studied for my thesis, and I'm wondering if there is a similar mechanism (type classes) to expresses that two numbers are addable (like a ...
0
votes
0
answers
60
views
Kotlin Result Function Chaining Patterns
Question for you smart people. I'm glad to see some functional objects in Kotlin such as Result, but I'm struggling how to use it effectively. Here's a couple of patterns that I came up with, but ...
0
votes
1
answer
61
views
How do I return a list of all matches to a dictionary lookup in C# functional/linq?
Basically attempting to
input a list of characters.
cross reference each character against a dictionary of char>string connections.
output a list of strings.
In normal C# I had it working similar ...
0
votes
2
answers
92
views
Scala: methods aren't functions because of JVM limitations?
I found it often mentioned that in Scala 2 attempts like
def f(x: Int): Int = x*x
val g = f // note the missing type
aren't possible because of "underlying limitations of the JVM how it treats ...
0
votes
1
answer
86
views
How do I extract parts of a function from a function in Haskell?
I'm trying to take a function of type (Either a b -> c) as a parameter and pass its methods f and g that it uses depending on the variable type in the form (f, g), but I'm not sure how to do so.
In ...
1
vote
1
answer
66
views
Why can some disjoint and exhaustive patterns not be represented as definitional equalities?
I am currently reading through Ulf Norell's PhD Thesis, where he describes the implementation of Agda.
In Chapter 2.2 (page 41), which is concerned with pattern matching with dependent types, he ...