Questions tagged [functional-programming]

1

votes
1

answer
47

Views

How to invoke a generic function inside another function with a timeout with java 8?

I have a function that gives me a state of service: public ServiceState getServiceState(){ return someService().getState(); //currently state return 'NOTACTIVE' } And when I invoke a certain method on the system, the service should be in active state after x amount of time (unknown time): someServi...
totothegreat
1

votes
3

answer
60

Views

Clojure zipper to remove all right siblings

I want to write a function for a zipper that removes all right siblings of a node while staying at the same location. (defn remove-all-rights-1 [loc] (if (zip/right loc) (recur (zip/remove (zip/right loc))) loc)) The problem here is that remove returns the location that would have preceded the curr...
erdos
1

votes
1

answer
86

Views

Updating a variable inside a function

I have created a function in SML that traverses the starting elements of a list and if first,second,third.. element are the same deletes these elements and updates a variable's value.What i have written: let val min=7 in fun seen2 (set:int list) = if hd set=hd(tl set) then min=min-1 seen2(tl set)...
1

votes
1

answer
103

Views

Issue in getting subtree in SML

I am stuck in coding where I have to get subtree for a given node in SML. The data type is below. datatype ctree = Empty | Node of char*ctree*ctree Now I have to write function which will return subtree rooted at a given node. I wrote a helper function 'nodeExist(n,tree)' which will check if the nod...
Sri
1

votes
1

answer
65

Views

Using an accumulator to sum up numbers in F#

I'm trying to solve a problem that requires me to sum up 2 numbers but I have to use an accumulator in my function. This is the math formula: sum(m, n) = m + (m + 1) + (m + 2) + · · · + (m + (n − 1)) + (m + n) Here is what I have so far: let rec g (m, n) = let rec gAcc m n a = match n with |...
1

votes
3

answer
57

Views

What exactly is a pure function when we are talking about a function within a function

I've learned that a pure function is a function that doesn't alter global state, period. If this is true, functions within functions can alter the state of the outer function and still be pure, correct? Example: function func1() { let name = 'My Name' func2() function func2() { // alter name here....
0oxl1
1

votes
1

answer
35

Views

Understanding how add method works in Isabelle

There is a custom add method in the book Concrete Semantics page 8. As follows the code and proof, the original name of the function is called add but I renamed it to add1 to avoid issues with the built-in method add in Isabelle: fun add1 :: 'nat ⇒ nat ⇒ nat' where 'add1 0 n = n' | 'add1 (Suc m...
Mario Burgos
1

votes
1

answer
39

Views

Use immutable.ListMap in place of mutable.LinkedHashMap

I want to use immutable data structure as much as possible. Very general case in our code base is use of mutable.LinkedHashMap. I want to replace this with immutable.ListMap in all non-performance critical code. General format that our code is having like mutable.LinkedHashMap initialization loop co...
user811602
0

votes
0

answer
3

Views

Getting a random number in a function in OCAML OR Telling compiler to evaluate function each time

I'm new to OCAML and was playing around with putting a marker on a random 5X5 square. I've written the example program below. 'silly_method1' works but notice that it takes an argument. I don't really have argument to pass in for what I want. I'm just asking for a random number to create my robo...
Dave
1

votes
1

answer
172

Views

Creating a list or sequence of numbers up to a certain value in F#

Suppose I want to create a list or sequence of all cubic numbers under 5555, or fibonnacci numbers under 4500 - How would I do this? I can generate a list or sequence of these , but I don't know how to make them terminate after a certain point. In the case of the fibonacci sequence it is difficult...
Dr. John A Zoidberg
1

votes
2

answer
114

Views

In R, how do I define a function which is equivalent to `deparse(substitute(x))`?

I want to write a function in R which grabs the name of a variable from the context of its caller's caller. I think the problem I have is best understood by asking how to compose deparse and substitute. You can see that a naive composition does not work: # a compose operator > `%c%` = function(x,y)...
Metamorphic
1

votes
2

answer
95

Views

What does “i.(string)” actually mean in golang syntax? [duplicate]

This question already has an answer here: Is this casting in golang? 1 answer I do not understand this syntax 1 answer I recently started looking for functional go examples and I found this function: mapper := func (i interface{}) interface{} { return strings.ToUpper(i.(string)) } Map(mapper, New(...
Daksh Miglani
1

votes
2

answer
64

Views

Scala: Design pattern for object / renderer for UI

What would be a good design to have renderer and object. I have made a few attempts but my code is really ugly right now. Let's say I have a class room and a class which is supposed to handle rendering it. Who should call renderer.render(room) or should it even be that way ? Should I have world.r...
Wonay
1

votes
4

answer
72

Views

Scala: Maintain child class in parent methods ?

When you have a parent: abstract class Parent { def something(arg: ???): Parent = ??? } and class Child extends Parent {} I would like val updatedChild = new Child().something(...) updatedChild to be of type Child and not of type Parent, is it possible ?
Wonay
1

votes
3

answer
127

Views

How to atomically check if a key exists in a map and add it if it doesn't exist

I am trying to generate a new key that doesn't exist in my map (atom), then immediately add it to my map and return the key. However, the check for the key and the update are not done atomically. I am wondering how to do this atomically so that it is safe for concurrency. Ideally this key is short e...
Anu Bandi
1

votes
2

answer
58

Views

Missing parameter type for expanded function while creating partially applied function

I am new to Scala and was reading about partially applied functions in Scala. I've a general function 'wrap' which can concatenate three strings. def wrap(prefix: String)(html: String)(suffix: String) = prefix + html + suffix When I try to make a specialized function like this val foo = wrap(_)('Hel...
victini
1

votes
2

answer
47

Views

Scala: Reuse Function Value

I have these 2 functions: 1) protected def withBagAsync(body: Bag => Future[Result]): Future[Result] = { //... implementation } 2) protected def withBag(body: Bag => Result): Future[Result] = withBagAsync(body??) I want to reuse the functionality of 1 from 2. But I can not figure out how to do that.
pme
1

votes
2

answer
133

Views

ES6 pass function as parameter example

I don't know JS/ES6 well enough to describe my question in code. So most of this question is conceptually and in pseudo code. Say I have a Contractor class like this: class Contractor { constructor(jobFn) { // save jobFn; } dailyRoutine() { // let result = DriveToWork() const result = 6 DoTheJob(re...
xpt
1

votes
1

answer
45

Views

Combining two anonymous functions

I'm trying to understand how to combine two anonymous functions in SML. Consider: val x = fn 5 => 5 | 6 => 6; val y = fn 3 => 3 | 2 => 2; I would like to create function z by combing x and y: val z = fn 5 => 5 | 6 => 6 | 3 => 3 | 2 => 2; How can I achieve it?
vesii
1

votes
2

answer
92

Views

How do I show relationships between type variables

For the types Door and Hallway: data DoorState :: Type where Opened :: DoorState Closed :: DoorState Locked :: DoorState deriving (Bounded, Enum, Eq, Ord, Show) data Door :: DoorState -> Type where Door :: {material :: String} -> Door s deriving (Show) data Hallway :: [DoorState] -> Type where Origi...
Vanson Samuel
1

votes
2

answer
43

Views

Ruby equivalent of lisp-like “apply”?

I would like to create an instance method that takes another instance method of its own class as a parameter, and then applies the passed method on the instance it's working on (known as self): class MyClass attr_reader :called_methods def initialize @called_methods = [] end def my_first_method! @ca...
Lori
1

votes
2

answer
54

Views

Functional Programming: How to handle complex data without bloated functions?

Lets say in your program you have defined a complex car object. That object holds a very long list of predefined key value pairs (wheels,engine,color, lights, amountDoors etc.), each being either a part number or a list of part number, or a specific value. //** PSEUDO CODE: var inputCar = { 'engine...
Marcus Blättermann
1

votes
2

answer
55

Views

Ramda: How to translate a normal application to a pipe or compose

This is a newbie question (I'm still quite new to Ramda and functional programming in general). I have a function with two arguments. For the sake of simplicity let's assume it just subtracts the numbers. I want to flip and curry its arguments. I have figured out how to do it manually, but it really...
J. Hesters
1

votes
4

answer
83

Views

Given a java Function, how can I update one function value?

If I have a function f in OCaml, I can just type let f x = if x=1 then 42 else f x If this would not hide the old definition of f, this would be exactly what I would want. Now I'm looking for an equivalent in Java, but with the additional constraint that the reference in Function f is updated. I can...
bruderjakob17
1

votes
1

answer
65

Views

Why are the controller actions in Phoenix passed as atoms instead of functions?

defmodule HelloWeb.Router do use HelloWeb, :router scope '/', HelloWeb do get('/', PageController, :index) end end In this example, why isn't the controller's function passed directly, like get('/', PageController.index)?
1

votes
1

answer
60

Views

Does the following Ramda/function programming pattern follow conventions/best practices?

Original export const isTimeStrValid = str => { return str.length >= 4 && moment(str, ['H:mm', 'HH:mm'], true).isValid(); }; Ramda export const isTimeStrValid = R.allPass([ R.pipe(R.length, R.gte(R.__, 4)), R.pipe( s => moment(s, ['H:mm', 'HH:mm'], true), R.invoker(0, 'isValid'), ), ]); The Ramda/fu...
Edmond C
1

votes
1

answer
44

Views

How to iterate over all combinations of two function arguments and return an 'n by m' matrix in r

I want to count the number of first, second, third etc. preferences that a candidate has received in a (randomly generated) election: library(tidyverse) library(magrittr) set.seed(42) results % t() %>% tbl_df() %>% set_colnames(c('A', 'B', 'C', 'D', 'E')) # A tibble: 10 x 5 A B C D E...
Jonathan Aron
1

votes
1

answer
35

Views

Can't compile example from book Advanced Scala with Cats

I'm reading the book and playing with examples there. The problem is I can't reproduce this example: type Logged[A] = Writer[List[String], A] // Example method that returns nested monads: def parseNumber(str: String): Logged[Option[Int]] = util.Try(str.toInt).toOption match { case Some(num) => Write...
faoxis
1

votes
2

answer
37

Views

APL - How can I find the longest word in a string vector?

I want to find the longest word in a string vector. Using APL I know that the shape function will return the length of a string e.g. ⍴ 'string' ⍝ returns 6 The reduce function allows me to map diadic functions along a vector but since shape is monadic this will not work. How can I map the shape...
awyr_agored
1

votes
1

answer
56

Views

How do error handling monads like Eithers achieve referential transparency?

From reading about FP, my understanding of the benefits of removing side-effects is that if all our functions are pure/have referential transparency (something that can only be achieved without side-effects), then our functions are easier to test, debug, reuse, and are more modular. Since exceptions...
suleydaman
1

votes
3

answer
48

Views

Join elem with next one in a functional style

I'm trying to find a way to 'join'/'groupby' 2 elements in a list as following : List('a','b','c','d') -> List('ab','bc','cd') With a functional style. Would someone know how to do this? Need I use reducer, fold, scan, other higher-order function?
Quentin Geff
1

votes
4

answer
67

Views

What is the best way to print all the dates contained on some objects dates ranges inside an array?

If I have an array of objects like this: { 'workPeriods': [ { 'user_id': '9345bf', 'startDate': '2018-02-05T05:00:00.000Z', 'endDate': '2018-02-09T05:00:00.000Z' }, { 'user_id': '80c3a9', 'startDate': '2018-02-12T05:00:00.000Z', 'endDate': '2018-02-16T05:00:00.000Z' }, { 'user_id': '35jh87', 'startD...
Leonardo Uribe
1

votes
1

answer
48

Views

Scala: Printing the ouput in proper data format using scala

I would like to display the data in proper format, I have the below code val maplist=List(Map('id' -> '1', 'Name' -> 'divya'), Map('id' -> '2', 'Name' -> 'gaya') ) val header=maplist.flatMap(_.keys).distinct val data=maplist.map(_.values) println(header.mkString(' ')) data.foreach(x => println(x.mk...
lak
1

votes
2

answer
72

Views

how to create an alist with initial values

I'm learning scheme (using guile) and I found the need to create an initial alist, with some keys and empty lists as their values. I was wondering what's the best practice when doing something like this. My goal is to keep this alist around so I can later add items to the lists. This is what I have...
rolando
1

votes
2

answer
107

Views

Scala - composing generic types

I want to create a generic interface which hides the implementation of the hash function on the key of a product (which is used to lookup products and for various caching and calculations outside the scope of the product itself). I want to tie the concrete implementation of the hash function to the...
Avner Barr
1

votes
1

answer
63

Views

How can I implement the function “divide” in a functional Divide-And-Conquer Java algorithm?

I am trying to implement a functional version of the Quicksort algorithm. My professor asked me to keep this as the signature: public static List myQuickSort(Function trivial, Function solve, Function divide, Function combine, List input) I created an auxiliary class named Pair, which goes like...
Alessandro Pezzotta
1

votes
0

answer
48

Views

How to test a function that has side effects?

Given a function that does some operation on a database for instance. In python, it would look like the following: def dao_transfer(cnx, account_id1, account_id2, money): spam = cnx.execute('query 1', account_id1) egg = cnx.execute('query 2', account_2, spam) return egg What I do in my unit tests i...
amirouche
1

votes
1

answer
110

Views

Functional Programming in Java 8

As for as I have understood that functional Programming means to give a different behavor implementations interface. Would that be better than I had to create a new Class and implemented that interface in it? I am not clear on this interface worldGreeting { String processName(String str); } public...
Waseem Saeed
1

votes
1

answer
139

Views

Error with bspline smoothing for functional data in R with high number of basis functions

I have this error in R, I can't solve it : Error in chol.default(temp) : the leading minor of order 445 is not positive definite In addition: Warning message: In smooth.basis1(argvals, y, fdParobj, wtvec = wtvec, fdnames = fdnames, : Matrix of basis function values has rank 799 < dim(fdobj$basis)...
Victoire Louis
1

votes
1

answer
45

Views

How do you add a new argument to a pure function without having to update all calls to the function?

I make a pure function (example in js, but the question doesn't depend on the language) with one input argument and call it all over my application. var day = 'Tuesday'; var doYouExist = function(you) { return !!you; } Then I realise that I should only check if you exist on Tuesdays so I decide to...
P0lska

View additional questions