functional-programming,lisp,common-lisp , LISP: read number from user and commpare with array index

LISP: read number from user and commpare with array index


Tag: functional-programming,lisp,common-lisp

Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare the user inputs and index of array ? other part on my question how we can specify the index of array in lisp ? for example I was did this program in a numerical programming language like C# but how I can do it in LISP ?

static void Main(string[] args)
        while (true)
            Console.Write("Enter the number:");
            string name = Console.ReadLine();
            string[] numbers = {"0","1", "2", "3", "4", "5"};
            string[] words = {"one", "two", "three", "four", "five" };
            for (int i = 0; i < numbers.Length; i++)
                if (name == numbers[i].ToString())


Common Lisp is multi-paradigm, not purely functional. There's really no reason to change your code algorithm from C#. If you want to write in a procedural style, you can continue to do so.

(defun main (&rest args)
  (declare (ignore args))   
     (princ "Enter the number:")
     (let ((name (read-line))
           (numbers #("0" "1" "2" "3" "4" "5"))
           (words #("one" "two" "three" "four" "five")))
       (loop for i from 0 upto (length numbers)
          when (equal name (elt numbers i))
          do (print (elt words i))))))

Unfortunately, your example doesn't work correctly in C#, so it's really hard to guess what you would want it to do in Lisp. The following is a general-purpose version that will do the same thing for any number (not just 0-4), but still follows the “shape” of your C# example.

(defun main ()
     (princ "Enter a number:")
     (let* ((*read-eval* nil)
            (number (read)))
       (format t "~&~r" (1+ number)))))


Return items of a list in Lisp

I have to write a program in Lisp that returns the first item of a list if it contains an even number of elements, and the last if it contains an odd number of elements. I need a little advice on where to start? I don't need whole program.

Erlang syntax error unclear

I just got started with Erlang. I am trying if statement. I found out one particular behavior which I do not understand. the following statement does work perfectly. some_comp(Arg1) -> if (cal(Arg1)>50000)->'reached'; true -> 'invalid' end. cal(Arg2)-> %% some calculation. However the following shows an error syntax near if: some_comp(Arg1)...

How to handle initial nil value for reduce functions

I would like to learn and use more functional programming in Swift. So, I've been trying various things in playground. I don't understand Reduce, though. The basic textbook examples work, but I can't get my head around this problem. I have an array of strings called "toDoItems". I would like...

Invalid specialized parameter in method lambda list

I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

Is this definition of a tail recursive fibonacci function tail-recursive?

I've seen around the following F# definition of a continuation-passing-style fibonacci function, that I always assumed to be tail recursive: let fib k = let rec fib' k cont = match k with | 0 | 1 -> cont 1 | k -> fib' (k-1) (fun a -> fib' (k-2)...

Printing ith row jth column value in lisp

I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made...

Idiomatic list construction

I'm very new to Haskell and functional programming in general, so I don't really know how to make this code idiomatic: type Coord = Double data Point = Point Coord Coord Coord deriving Show type Polyline = [Point] -- Add a point to a polyline addPoint :: Polyline -> Point...

In underscore/lodash, how to avoid duplicate calculation in a `map` method?

Here is my code: var transformed = _(original).map(function (c) { return { lat: wgs2gcj(c.latitude, c.longitude).lat lng: wgs2gcj(c.latitude, c.longitude).lng } }); Let's say wgs2gcj is a function from a third-party library and will take a long time to compute. Is there a way to do the calculation only once?...

Properly implement F# Unit in C#

This question is not about C#/F# compatibility as in this one. I'd like to know the proper way to implement a type like F# Unit in place of using void. Obviously I'll discard this result and I'll not expose this type to the outside world. Wondering if an empty class...

Convert loop to Maybe monad

Recently I tried applying Maybe monad pattern in my C# code using this library. What I found difficult to grasp was converting such a function into Maybe paradigm: public Maybe<object> DoSomething(IReader reader) { while (true) { var result = reader.Read(); if (result == null) return Maybe<object>.Nothing; if (result.HasValue) return new...

In simplest term, what is currying and why should this approach be favored over traditional programming paradigm?

I am having hard time understanding currying through several sources on web . Isn't there more intuitive example of currying? Also, what are its advantages over traditional programming paradigm ? Is currying possible to achieve on non-functional programmming?...

Using Diagrams library in haskell (draw binary trees)

I am trying to use the Haskell Diagrams library for drawing binary trees. This is my tree type: data Tree a = Empty | Node { label :: a, left,right :: Tree a } leaf :: a -> Tree a leaf a = Node a Empty Empty This is a...

Lazy functions evaluation in swift

Wondering is it possible to evaluate a simple if statement lazily. Below is an example that will print "this is foo" and "this is bar", but I really want to make it print only the first string: func foo() { println("this is foo") } func bar() { println("this is bar")...

Accessing call stack depth in Scheme

In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

Functional way of doing a loop of operations on an array

I currently have a Java program which does something like the following: int nvars = 10; long vars[] = new long[nvars]; for(int i = 0; i < nvars; i++) { vars[i] = someFunction(i); anotherFunction(vars[i]); } I am converting it into Scala code and have: val nvars: Int = 10 val...

If strings are vectors, why are they immutable?

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Scala wrong forward reference

I am working through some of the exercises in: Functional Programming in Scala specifically problem 5.2. The issue is that with the following code which I have pieced together from the answer key. sealed trait Stream[+A] { def take(n: Int): Stream[A] = this match { case Cons(hs, ts) if n...

Having trouble stepping through function that reduces an array of functions

When using the reduce method on an array of functions I am having difficulty tracing through how reduce works on the array exactly. comboFunc(num, functionsArr) { return functionsArr.reduce(function (last, current) { return current(last); }, input); } so with functionsArr = [add, multi] and the functions add and multi being function...

Insertion into a list doesn't reflect outside function whereas deletion does?

I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?

I apologize if this has an obvious answer. I would like to find a lazy functional programming language where the following pseudo code makes sense: let f = function(x) { let y = x*x // The variables y and z let z = y*2 // are local return z }...

Lazy concat in Immutable.js?

Is there a way to do a lazy concat of two sequences in Immutable.js? Specifically, I have this algorithm that flattens a tree into a breadth-first sequence: var Immutable = require('immutable'); var tree = { value: 'foo', children: [ { value: 'bar', children: [ { value: 'barOne'}, { value: 'barTwo'}...

First word of binary string erlang

I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Value from binding in LFE interpreter using Erlang

I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

Collapse similar case statements in Scala

Is there an elegant way to do something like the following example using just one case statement? foobar match { case Node(Leaf(key, value), parent, qux) => { // Do something with parent & qux } case Node(parent, Leaf(key, value), qux) => { // Do something with parent & qux (code...

Hook into GHC runtime system

I have been looking at how transactional memory is implemented in Haskell, and I am not sure I understand how the STM operations exposed to the programmer hook into the runtime system functions written in C. In ghc/libraries/base/GHC/Conc/Sync.hs of the git repo, I see the following definitions: -- |A monad...

functional way to accumulate pairs in java8

Here's some imperative code that I'm trying to translate into functional programming code: public class Person { String name; Token token; public Person(String name, Token token) { = name; this.token = token; } } public class Token { String id; boolean isValid; public Token(String id, boolean isValid) {

Backquote String Interpolation

Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

Exceed evaluation depth when forward function in Emacs Lisp

Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

Questions about Vars Clojure

I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable? I can change the value of the var after, so is it really that different...

What is Anamorphism - example in C#

I am trying to wrap my head around the concept of anamorphism. In functional programming, an anamorphism is a generalization of the concept of unfolds on lists. Formally, anamorphisms are generic functions that can corecursively construct a result of a certain type and which is parameterized by functions that determine...

How to effectively get indices of 1s for given binary string using Scala?

Suppose we have a binary string such as 10010010. All I want is a function returning indices of 1s for that string: indicesOfOnes("10010010") -> List(0, 3, 6) indicesOfOnes("0") -> List() And what I implemented is: def indicesOfOnes(bs: String): List[Int] = { val lb = ListBuffer[Int]() bs.zipWithIndex.foreach { case (v, i)...

Declaring a Ruby lambda with a yield

I'm writing a method that splits an array of struct into a couple of different, arrays while also eliminating elements with nil values. What I want to write is: def my_func(some_data) f = lambda{|data|{|m| yield(m).present? }.map { |m| [, yield(m)]}} x = {|m| m.first_var} y = {|m|...

Java 8 Lambda expressions for solving fibonacci (non recursive way)

I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc. However can they be utilized effectively in solving problems like Fibonacci where the current value depends on sum of previous two values. I...

Joining a collection based on members of the type

I have a class A and its members b and c. Now I construct the List<A> with this: add(new A().setb("abcd").setc("123456")); add(new A().setb("efgh").setc("789101")); add(new A().setb("ijkl").setc("112345")); I want to transform this List to string which looks like this abcd,123456 efgh,789101 ijkl,112345 Now the very obvious way would be to have a StringBuilder...

Is there a functional way to set a variable in javascript?

I am looking for something like this: set("variablename", "value"); Why I need this? I want to write the following without creating a new function: navigator.getUserMedia({ audio: true }, success, fail); var success = function(stream) { var source = audioCtx.createMediaStreamSource(stream); } ...

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Structuring large Lisp applications

I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

How do you represent nested types using the Scott Encoding?

An ADT can be represented using the Scott Encoding by replacing products by tuples and sums by matchers. For example: data List a = Cons a (List a) | Nil Can be encoded using the Scott Encoding as: cons = (λ h t c n . c h t) nil...

Purity, Referential Transparency and State Monad

I'm currently designing a numerical algorithm which as part of its operations requires updating a vector of doubles many times. Due to the fact that the algorithm has to be as space and time efficient as possible, I do not want to code the traditional type of FP code which...

Common Lisp Object System method execution order

I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

Standard ML / NJ: Loading in file of functions

I'm trying to write a bunch of functions in an SML file and then load them into the interpreter. I've been googling and came across this: Which has this section: Loading ML source text from a file The function use: string -> unit interprets its argument as a file...

Easier way to apply multiple arguments in Haskell

Given value f with type :: Applicative f => f (a -> b -> c), What's the best way to map arguments to the inner function. So far I've found the following: (\x -> x a b) <$> f (flip ($ a) b) <$> f ($ b) <$> ($ a)...

First Object in Set> that satisfies a predicate

Abstract idea I want to get the first value coming out of a set of Futures, that satisfies a given predicate. If a satisfying value is found, all other Futures should be cancelled. If no value is found after all Futures have returned the execution should be terminated (by returning...

What is the type of the variable in do-notation here in Haskell?

The codes below looks quite clear: do x <- Just 3 y <- Just "!" Just (show x ++ y) Here the type of x is Num and y is String. (<- here is used to take actual value out of the Monad) However, this snippet looks not so clear...

EVAL/APPLY: too many arguments given to F

Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Apply a list of Functions to a Java stream's .map() method

I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this: List<NameValuePair> paramPairs = getParamPairs(); List<NameValuePair> newParamPairs = .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp)) .flatMap(Collection::stream) .collect(toList()); But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions....

Why is `++` for Haskell List implemented recursively and costs O(n) time?

As I understood, a List in Haskell is a similar to a Linked-List in C language. So for expressions below: a = [1,2,3] b = [4,5,6] a ++ b Haskell implement this in a recursive way like this: (++) (x:xs) ys = x:xs ++ ys The time complexity for that...

Remove item from array using foreach - JavaScript [duplicate]

This question already has an answer here: How do I remove an element in a list, using forEach? 2 answers Is it possible to remove something from an array using foreach? var array = [1,2,3,4,5,6,7,8]; array.forEach(function(data){ if (data == 4) { // do something here } }); console.log(array); ...

Why use Object.create inside this reduce callback?

So while working on #19 of this fine tutorial -, I find that the exercise works without using Object.create. (See the commented-out lines) 1. So what is the point of creating that copy of the accumulatedMap? Other than showing that it is possible... function() { var videos = [...