Functional programming Which functional language(s) does Clojure share the most in common with?

I don't know much about functional programming but am interested in learning Clojure. Are there any functional languages that would be a good point of reference to understand how functional programming works in Clojure? Or is Clojure different enough in its functional programming approach that I would be better off to just focus on Clojure's functional features by themselves?

Functional programming What is the correct term for the following functional programming pattern?

I've heard it referred to as a stream, as an infinite list, and sometimes even as a lazy sequence. What is the correct term for the following pattern? (Clojure code shown) (def first$ first) (defn second$ [str] (cond (empty? str) () true ((first (rest str))))) (defn stream-builder [next_ n] (cons n (cons (fn [] (stream-builder next_ (next_ n))) ()))) (defn stream [str n] (cond (= 0 n) () true (cons (first$ str) (stream (second$ str) (- n 1))))) (def odd (stream-bui

Functional programming Practical application of SKI calculus and BCKW

I can understand how to create and think about the SKI and BCKW calculus, but I am never able to find practical uses. Maybe I am not looking deeply enough? That is, I wonder if (an example only please, I am not implying this is true) Java Servlets use S extensively and Python generators are an example of BCW and I am just unable to see through the forest of trees?

Functional programming Try to further understanding the interface/module of OCaml

I understand in OCaml there are concepts of interfaces and module. And I understand how to use them now. However, what I don't understand is how to fully utilise them. For example, in Java, let's say we have a interface Map and we also have Hashtable and HashMap that implement Map. In code, I can do like: Map m = new Hashtable(); m.put("key", value); Someday, if I change my mind, I can change to Hashmap very quickly by changing Map m = new Hashtable(); to Map m = new HashMap();, right

Functional programming Do I need to call Random.self_init in OCaml?

First of all, I don't care about seed in this question. My question is that whether I should call Random.self_init every time I want a fresh start in my function? let shuffle l = Random.self_init (); let tagl = (fun x -> (Random.bits (), x)) l in (fun x -> snd x) (List.sort compare tagl);; for example, in the above code, is Random.self_init () necessary or not?

Functional programming How to perform side-effects in pure functional programming?

I am dealing with the concept of functional programming for a while now and find it quite interesting, fascinating and exciting. Especially the idea of pure functions is awesome, in various terms. But there is one thing I do not get: How to deal with side-effects when restricting yourself to pure functions. E.g., if I want to calculate the sum of two numbers, I can write a pure function (in JavaScript): var add = function (first, second) { return first + second; }; No problem at all. But

Functional programming Scheme language case conditional with multiple tests?

What I'm trying to do is shown below in pseudo code: case (test0, test1) begin (false,false): statement 0; (false,true): statement 1; (true,false): statement 2; (true,true): statement 3; end How to do it in scheme using the case conditional? The problem is that case uses the eqv? predicate which it seems will always return false (because (eqv? '(#f . #f) '(#f . #f)) evaluates to #f). Would appreciate any reasonably concise way of expressing above pattern in scheme (other t

Functional programming How do you evaluate boolean and then execute statements in java 8 with Optional?

How can I refactor this snippet in Java 8 Optional? Can I use map with OrElseThrow for this? What is a cleaner way of writing this code? public void updateMyDao(MyObj objToUpdate) { if(myOptional.isPresent()) { MyDao oq = myOptional.get(); if(!oq.getReferenceId().equals(objToUpdate.getId())) throw new RuntimeException("Bad Move!"); oq.setAttribute(objToUpdate.getAttribute()); ..... ..... } else { throw new RuntimeException("Entity was not foun

Functional programming Storing user input information in functional programming (Erlang) using only immutable variables

As a beginner in Erlang, I am working my way through the Programming Erlang book (2nd ed). I have a very hard time grasping how to store and periodically update external information (such as intermittent user input) using the principles of functional programming exclusively. To take my present example, I am now in the beginning of the concurrent programming section (Chapter 12) where the book talks about the area server. Below is my variant of it. As an exercise, I am trying to add to this m

Functional programming Scheme Function: (show-up-to-n '(4 6 3 -8 3 4) 5) ==> (4 3 -8 3 4)

i am trying to write a function in Scheme that takes in a list and an integer and outputs the same list minus all the members less than the integer... please help. I seem to be unable to add the numbers into a new list that can be outputed. (define result '()) (display result) (define nums-less-than-x (lambda (lst x) (define impl (lambda (l1 b result) (if (null? l1) result (begin (if (> b (car l1)) (begin (cons (car l1) result)

Functional programming Can't open Llvm in ocaml

I'm trying to use llvm binding in ocaml, in my file, I have one line of code: open Llvm When I run the command ocamlbuild -use-ocamlfind test.byte -package llvm I get this result: + ocamlfind ocamldep -package llvm -modules > ocamlfind: Package `llvm' not found Command exited with code 2. Compilation unsuccessful after building 1 target (0 cached) in 00:00:00. What did I do wrong in this? Thanks. BTW, the _tag file contains: "src": traverse <src

Functional programming How to combine equal sequence elements (functional programming)?

I want to write a function that takes in a sequence <1,1,2,2,3> and returns the sequence with equal elements grouped like <<1,1>, <2,2>, <3>>. I'm using sequences, not lists, but some of the functions are similar. Some of the functions I am thinking of using are map, reduce, tabulate, filter, append etc.. Reduce takes in an associative function and returns the sequence that is "reduced" by that operator. So, reduce op+ 0 <1,2,3> = 6. My first thought was to use map to rai

Functional programming SICP 3.6 - Rand procedure and local state variables

I'm having difficulties with exercise 3.6 in SICP. They give the following code for a pseudo-random number generator: (define rand (let ((x random-init)) (lambda () (set! x (rand-update x)) x))) To which I added, for testing purposes: (define (rand-update x) (+ x 1)) (define random-init 4) Repeated applications produces > (rand) 5 > (rand) 6 > (rand) 7 as hoped, although I can't see why this works. Anyway, exercise 3.6 asks us to modify rand so that it takes

Functional programming Immutable js - best way to extract values from a deeply nested object in a declarative way?

Let say I get a json back from an API call with this shape once parsed: const foos = { foo1: { bar1: [{a:1},{a:2},{a:3}], bar2: [{a:4},{a:5},{a:6}], bar3: [{a:7},{a:8},{a:9}] }, foo2: { bar4: [{a:10},{a:11},{a:12}], bar5: [{a:13},{a:14},{a:15}] } } Then, I wrap it in fromJs() to make it immutable. Next, I need to iterate over that object to extract values this way and do whatever I want with it: var obj = {aValue: 0} Object.keys(foos).forEach( key => { O

Functional programming Construct list terminated with a different type

Do I need a bespoke sum type to be able to define a data type that is a list of type A, where the last element is of type B (and thus have to reimplement all the nice functions defined on it). type ListTerminatedWith<'a,'b> = | Cons of 'a * ListTerminatedWith<'a,'b> | Nil of 'b ok, so the obvious thing is: type ListTerminatedWith<'a,'b> = List<'a> * 'b but, actually I only want to append the terminating value to the list when I get there (really the question i

Functional programming Why does array_map throw a warning when the closure raises an exception?

I've recently started programming with PHP again, after a long stint with other languages during which i've developed a more functional style - which i'm hoping to try and maintain. I've noticed some weird behaviour, which I managed to distill into a testcase that I'm hoping someone can explain. $func = function($item) { if ($item == 0) throw new Exception("Can't do 0"); return $item; }; try { array_map($func, array(1, 2, 3, 0, 5)); } catch (Exception $ex) { echo "Coul

Functional programming Explanation of "Lose your head" in lazy sequences

In Clojure programming language, why this code passes with flying colors? (let [r (range 1e9)] [(first r) (last r)]) While this one fails: (let [r (range 1e9)] [(last r) (first r)]) I know it is about "Losing your head" advice but would you please explain it to me? I'm not able to digest it yet. UPDATE: It is really hard to pick the correct answer, two answers are amazingly informative. Note: Code snippets are from "The Joy of Clojure".

Functional programming Can I use Gambit-C, Mlton, or Chicken Scheme with Google's Native Client

Those functional language compilers can each compile a functional language to C code. Google's NaCl SDK can compile C. Is it reasonable to create Native Client applications by compiling first with one of those other compilers and running the result through google's Native Client SDK? Anyone done this or have concrete info about possibilities, pitfalls, limitations? Thanks much!

Functional programming OCaml count the negatives

I'm really stuck on how to go about this I am asked to count the number of negatives within the list, I would have submitted the assignment with: let nneg = [4; 9; -5; 0; -5; 1];; List.filter nneg (fun-> (-)) List.filter nneg (fun x -> x < 0) but it's not an "int list -> int" but instead an "int list" so i started this but i can't figure it out for the life of me how to pattern match it: let rec rev nneg = match nneg with | [] -> 0 | head::tail ->(filter tail<

Functional programming Haskell-like libraries for Standard ML

Can anyone recommend a library extension for Standard ML with similar strength as, and preferrably looking like, Prelude for Haskell? Preferrably one that works for many ML implementations, i.e. built with only the existing standard library and itself. One library I have found is MyLib, which does not resemble Prelude particularly.

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

I write a ocaml program that parse an arithmetic expression by parser combinator. type 'a parser = char list -> ('a * (char list)) list let return (x: 'a): 'a parser = fun input -> [x, input] let fail: 'a parser = fun _ -> [] let ( >>= ) (p: 'a parser) (f : 'a -> 'b parser): 'b parser = fun input -> (fun (x, i) -> f x i) (p input) |> List.flatten let ( ||| ) (p: 'a parser) (q: 'a parser) = fun input -> (p input) @ (q input) let token: (char pars

Functional programming Standard ML: Modify depth function for binary tree

I'm given a depth function for a binary tree as follows: fun depth Empty = 0 | depth(Node(t_1, _ t_2)) = max(depth t_1, depth t_2) + 1; Suppose I want to modify this depth function such that a single node will have depth 0 (as it is, a single node will have depth 1). How would I go about doing this? I was thinking: fun depth Empty = 0 | depth(Node(Empty, _, Empty)) = 0 | depth(Node(t_1, _, t_2)) = max(depth t_1, depth t_2) + 1; Does this look right? Thanks, bclayman

Functional programming What are the usual higher-order primitives on lists in functional programming? (map, fold, and?)

What do you usually do with a list in purely functional programming? Obviously we have map f [x0; x1; x2] which produces [f x0; f x1; f x2] and fold f acc [x0; x1; x2] which produces f (f (f acc x0) x1) x2). For map, no information is transmitted between calls to f; for fold, all the information produced by f is re-injected in the next call through the accumulator acc. I've also seen things like flatmap that concatenates the lists produced by map f when f returns a list and for_all that appli

Functional programming Elm : extract a record values from a list of string

I try to make a function which take a record and a list of property names and return the values as a list of string: Model -> (List String) -> (List String) The goal is later to be able to render dynamically a record into an HTML table : Model -> (List String) -> (Html Cmd) I succeed to implement this: import Html exposing (text) type Field = FieldInt Int | FieldString String type alias Model = { name: Field , age: Field } user1 = Model (FieldString "foo") (Field

Functional programming Cannot find function `jsx:is_json/1` although jsx is included and compiled

I am writing a webapp using Erlang toolchain (OTP, rebar3, cowboy, jsx...). The following code does not work because jsx:is_json/1 cannot be found during runtime. handle_login(Req, State) -> {ok, Data, _} = cowboy_req:body(Req), case jsx:is_json(Data) of false -> cowboy_req:reply(400, [ {<<"content-type">>, <<"application/json">>} ], <<"Invalid JSON">>, Req); Stacktrace: {[{reason,undef}, {mfa,{erbid_api_ha

Functional programming BDD/ Test driven design in functional programming?

I am reading the "Test-Driven Development By Example" book by Kent Beck (pdf available here) in which he discusses the multi-currency money problem and designs a solution step by step, by introducing tests and consequently specifying the public methods for its classes and repeatedly refactoring to accommodate new tests/behaviours. He starts by having Franc and Dollar classes. Having then contemplated on the interface of these classes and having looked at the code and spotted duplication, he ref

Functional programming Print

I'm trying to get SML/NJ to print out a large integer of type However the function print(Int.toString(some_large_int)) does not work because Int.toString works only for the int type and not the Is there any way to print IntInf in the stdout?

Functional programming How to join arrays like JavaScript's destructuring?

I want to make a function that receives a Vec and a position to change a number. In JavaScript, this is really simple: function replaceNumber(line, position, number) { return [ ...line.slice(0, position), number, ...line.slice(position+1, line.length) ] } How can I make a similar function in Rust? I tried this: fn replace_number(line: Vec<i32>, point: i32, number: i32) -> Vec<i32> { return [ &line[0..point as usize], &[number],

Functional programming Point-free programming puzzle

I have a function that, written with anonymous functions, would hydrate an array of IDs using a list of objects, matching on the id property. const objectsList = [{ id: 1, ... }, { id: 2, ... }] => R.find(R.propEq('id', id), objectsList)) (I know it's silly to look up objects this way -- inefficient, etc. -- let's ignore that for the moment.) So, I want to do this point-free, and I'm getting stuck. This was by best attempt:'id', R.__), objects)) But

Functional programming Algorithm for generating n-tuples of an m-set

I am trying to implement an algorithm in Racket (without using loop), generate-tuples, that consumes a list of length m and a natural number n, and produces all possible n-tuples of the m-set of the elements in that list. For example: (check-expect (generate-tuples '(+ -) 3) '((+ + +) (+ + -) (+ - +) (+ - -) (- + +) (- + -) (- - +) (- - -))) I am having a hard time coming up with a functional solution. I already implemented an algorithm that generates all possible permutations o

Functional programming Trouble with equation for tick in Wadler, »Monads for functional programming«, section 3

In Wadler's Monads for functional programming I'm looking at the equation tick ✭ λ().m = m ✭ λ().tick in section 3 (in the context of State Monad). It is claimed that it holds so long as tick is the only action on state within m. I fail to understand how this can be the case. Doesn't the left term have the type of m while the right term has the type of tick : M ()? Moreover, if the type of m isn't M (), the types of the operands of ✭ are mismatched on the right-hand side. I looked

Functional programming In functional programming, is "saving the state" of an algorithm at the recursive function argument cheating?

for instance, lets suppose we had to write an algorithm to get the max value of an array of integers, could we still call the code functional if we make the recursive function return various information that simulates an assignment to a global object? an exemple: function getMax(array, props={}) { const {index = 0, actualMax = array[0]}= props ///initial props const arrayNotEnded = array[index + 1] !== undefined if (arrayNotEnded) { const maxOf= (a, b) => a > b ? a : b

  1    2   3   4   5   6  ... 下一页 最后一页 共 11 页