I'm trying to use scheme to write a function f that takes a number n and a function g and returns a list of lists of length n, but according with booleans according to the pattern indicated by g. For example, the function f should take n say 3 and the function g which makes every 3rd item on the list a true. It should return this:
(list (list true true false)
(list true true false)
(list true true false))
I have no idea where to start with this, so any help or tips would be greatly appreciated. THanks!
Key to this looks like using map.
In short, map takes a function and a list, and applies the function to that list, returning the modified list.
To do this, as I'm assuming you don't want a direct solution, I'd first construct your list of lists (just use an accumulator -- count down -- to make the list as long as needed, and use cons and list and quote for everything else.
Then simply apply map (probably twice, depending on how you implement your solution) to the list of lists. (eg list l and function fn: (map fn (car l)) and recur with the cdr of l and cons the results back together).
Good luck! Hope this helps!
I don't quite follow what you're trying to do, but in addition to map, you might find build-list to be useful. build-list takes a number and a procedure, takes the range from 0 to that number less 1, and maps your procedure over that range. e.g.
> (build-list 5 (lambda (x) (* x x)))
(0 1 4 9 16)
Related
I have this assignment:
Consider a list where every element is a nested list of length 2. The first
element of each nested list is either a 0 or a 1. The second element of each nested list
is some integer. An example input in Scheme is written below.
'((0 1) (1 2) (1 3) (0 4) (0 3))
For the purposes of this question, let’s call the first element of each nested list the
key and the second element of the nested lists the value. Now consider a function,
count_by_cat, that takes such a list as input and yields a two-element list where
the first element is the sum of the values of all nested lists with 0 as the key,
and
the second element is the sum of the values of all nested lists with 1 as the key
Implement count_by_cat in
(a) Racket, and
(b) ML.
It might be helpful to create helper functions. Also do not forget about map and filter
(filter is not a built-in in ML).
I'm new to Racket and ML. I'm stuck at using accessing lists and stuff in Racket. Some help with ML would also be great.
Well you're suggested to use higher order functions like map and filter.
And indeed it is easy to manipulate our data as a whole instead of focusing, mentally, on one element at a time. Which approach (i.e. the former one) some might argue, is the essence of functional programming paradigm.
In Racket,
(define (count_by_cat ls)
"return a two-element list"
(list
;; .....
;; ..... ))
where the first element is the sum of
(sum-of
the values of all nested lists
(map value
with 0 as the key
(filter (lambda (x) (= 0 (key x))) ls)))
and the second element is the sum of the values of all nested lists
(sum-of
(map value
with 1 as the key
(filter (lambda (x) (= 1 (key x))) ls))) ))
And so we need to define the helper functions accessing the nested lists,
(define (key n) (car n))
(define (value n) (cadr n))
and also the sum-of function, for summing up the numerical values in a list:
(require math/base)
(define (sum-of ls)
(sum ls))
This was easy to write, and will be easy to maintain.
The more performant code would do everything in one pass over the input, like is shown in the other answer. It has all the logic fused into one loop body. It could be more brittle to write and maintain.
The hint about map and filter is a bit of a red herring (As well as being wrong about them not being in ML languages); a helper function is very useful, but it's a fold you want, which basically calls a function with the current element of a list and an accumulator value, and uses what it returns as the accumulator for the next element and ultimately the return value of the entire fold.
For example, in ocaml, using a fold to sum a list of integers:
let sum = List.fold_left (+) 0 [ 1; 2; 3; 4; 5 ];;
((+) is the function version of the infix operator +).
Or your problem in Racket, using the for/fold comprehension, and returning two values instead of a two-element list, which is more idiomatic in Racket and Scheme (In ocaml and presumably Standard ML, you'd return a two-element tuple instead of a list, and take a list of tuples).
(define (count-by-cat lol)
(for/fold ([zero-sum 0]
[one-sum 0])
([elem (in-list lol)])
(case (first elem)
[(0) (values (+ zero-sum (second elem)) one-sum)]
[(1) (values zero-sum (+ one-sum (second elem)))])))
You could also use foldl, but for/fold is often easier to use, especially when working with multiple values or other non-trivial cases.
Can someone please help me with the below,
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
I do not understand how the above works. If we had something like (+3) 10 surely it would produce 13? How is that f (f x). Basically I do not understand currying when it comes to looking at higher order functions.
So what I'm not understanding is if say we had a function of the form a -> a -> a it would take an input a then produce a function which expects another input a to produce an output. So if we had add 5 3 then doing add 5 would produce a function which would expect the input 3 to produce a final output of 8. My question is how does that work here. We take a function in as an input so does partial function application work here like it did in add x y or am I completely overcomplicating everything?
That's not currying, that's partial application.
> :t (+)
(+) :: Num a => a -> a -> a
> :t (+) 3
(+) 3 :: Num a => a -> a
The partial application (+) 3 indeed produces a function (+3)(*) which awaits another numerical input to produce its result. And it does so, whether once or twice.
You example is expanded as
applyTwice (+3) 10 = (+3) ((+3) 10)
= (+3) (10+3)
= (10+3)+3
That's all there is to it.
(*)(actually, it's (3 +), but that's the same as (+ 3) anyway).
As chepner clarifies in the comments (quoted with minimal copy editing),
partial application is an illusion created by the fact that functions only take one argument, and the combination of the right associativity of (->) and the left associativity of function application. (+) 3 isn't really a partial application. It's just [a regular] application of (+) to an argument 3.
So seen from the point of view of other, more traditional languages, we refer to this as a distinction between currying and partial application.
But seen from the Haskell perspective it is all indeed about currying, i.e. applying a function to its arguments one at a time, until fully saturated as indicated by its type (i.e. a->a->a value applied to an a value becomes an a->a value, and that then becomes an a value when applied to an a value in its turn).
I'm struggling with the syntax with Haskell. It's very simple, but i'm stuck.
I'm trying to write a findMin function that takes a list and finds the minimum. Here's my code, I have tried so many syntactical things that I'm up for any help I can get.
findMin [] = [0]
findMin list = if any < head list then findMin(tail) else take 1
And i get all sorts of type errors. What is going wrong??
(if it helps at all i have a background in object oriented programming)
I see that you've got things figured out in the comments but I'll add some things here hopefully to help. I also feel like I should quickly mention that Haskell already has a minimum function just in case anyone stumbles upon this who isn't just trying to learn the language and actually needs the function for something.
First of all let's talk about types. I would normally expect a findMin style of function to return the minimum value rather than that value inside a list so the type will be:
findMin :: (Num a, Ord a) => [a] -> a
The things before => add context to the function type. This restricts all the things that a can be to only be things that have order (otherwise how can we find a minimum). Secondly Num a forces a to be a number, this is necessary because you specified that the case for the empty list should be 0.
I'll explain 2 other ways to write the findMin function, trying to make them more concise than your definition (one of the benefits of Haskell is how concise it can be and I also find it helps when learning to see the multiple possibilities). The first will be using recursion and guards the second will be using a list comprehension.
We can't do much with findMin [] = 0 so we'll move onto the lists with stuff in them.
We need to be careful with a recursive definition because eventually we will evaluate findMin [] and always get 0 so we need to stop the recursion before that by defining a case for a single value:
findMin [x] = x
When passing a list as an argument to a function you can separate out its elements and give them each a name so (x:xs) means a value x is the first element followed by a list of elements xs.
For this definition we will define the first two elements on their own followed by the rest of the elements:
findMin (x:y:xs)
| x < y = findMin (x:xs)
| otherwise = findMin (y:xs)
The guards allow us to have multiple definitions for the function depending on a condition. If x < y we want to get rid of y as it cannot be the minimum so we find the minimum of x and the remaining elements, xs. If x is not smaller than y then the minimum value is either y or one of the values in xs.
The second way to define this function is using a list comprehension (this is my favourite as it is particularly concise).
We aren't using recursion so we don't need the case for one element we can keep our definition for an empty list and go straight to any list with elements:
findMin xs = head [x | x <- xs, all (>= x) xs]
So what's going on here? [x | x <- xs] creates a list of x values where x is all the elements from xs. We then add a condition to say we only want those values if all (>= x) xs meaning if all elements of xs are greater than or equal to xs.
This results in a list of the minimum elements. This might have one element if the minimum occurs once or it may have several if it occurs multiple times. Either way they are all the same so we just take the first using head.
Hope this helps and hope you have fun learning Haskell. Feel free to ask if you have any questions :)
In ghci this function seems to do your trick:
let findMin x = if length x > 1 then min (head x) (findMin (tail x)) else head x
I'm learning as I try to answer some questions here, so any feedback would be appreciated.
Which are the uses for id function in Haskell?
It's useful as an argument to higher order functions (functions which take functions as arguments), where you want some particular value left unchanged.
Example 1: Leave a value alone if it is in a Just, otherwise, return a default of 7.
Prelude Data.Maybe> :t maybe
maybe :: b -> (a -> b) -> Maybe a -> b
Prelude Data.Maybe> maybe 7 id (Just 2)
2
Example 2: building up a function via a fold:
Prelude Data.Maybe> :t foldr (.) id [(+2), (*7)]
:: (Num a) => a -> a
Prelude Data.Maybe> let f = foldr (.) id [(+2), (*7)]
Prelude Data.Maybe> f 7
51
We built a new function f by folding a list of functions together with (.), using id as the base case.
Example 3: the base case for functions as monoids (simplified).
instance Monoid (a -> a) where
mempty = id
f `mappend` g = (f . g)
Similar to our example with fold, functions can be treated as concatenable values, with id serving for the empty case, and (.) as append.
Example 4: a trivial hash function.
Data.HashTable> h <- new (==) id :: IO (HashTable Data.Int.Int32 Int)
Data.HashTable> insert h 7 2
Data.HashTable> Data.HashTable.lookup h 7
Just 2
Hashtables require a hashing function. But what if your key is already hashed? Then pass the id function, to fill in as your hashing method, with zero performance overhead.
If you manipulate numbers, particularly with addition and multiplication, you'll have noticed the usefulness of 0 and 1. Likewise, if you manipulate lists, the empty list turns out to be quite handy. Similarly, if you manipulate functions (very common in functional programming), you'll come to notice the same sort of usefulness of id.
In functional languages, functions are first class values
that you can pass as a parameter.
So one of the most common uses of id comes up when
you pass a function as a
parameter to another function to tell it what to do.
One of the choices of what to do is likely to be
"just leave it alone" - in that case, you pass id
as the parameter.
Suppose you're searching for some kind of solution to a puzzle where you make a move at each turn. You start with a candidate position pos. At each stage there is a list of possible transformations you could make to pos (eg. sliding a piece in the puzzle). In a functional language it's natural to represent transformations as functions so now you can make a list of moves using a list of functions. If "doing nothing" is a legal move in this puzzle, then you would represent that with id. If you didn't do that then you'd need to handle "doing nothing" as a special case that works differently from "doing something". By using id you can handle all cases uniformly in a single list.
This is probably the reason why almost all uses of id exist. To handle "doing nothing" uniformly with "doing something".
For a different sort of answer:
I'll often do this when chaining multiple functions via composition:
foo = id
. bar
. baz
. etc
over
foo = bar
. baz
. etc
It keeps things easier to edit. One can do similar things with other 'zero' elements, such as
foo = return
>>= bar
>>= baz
foos = []
++ bars
++ bazs
Since we are finding nice applications of id. Here, have a palindrome :)
import Control.Applicative
pal :: [a] -> [a]
pal = (++) <$> id <*> reverse
Imagine you are a computer, i.e. you can execute a sequence of steps. Then if I want you to stay in your current state, but I always have to give you an instruction (I cannot just mute and let the time pass), what instruction do I give you? Id is the function created for that, for returning the argument unchanged (in the case of the previous computer the argument would be its state) and for having a name for it. That necessity appears only when you have high order functions, when you operate with functions without considering what's inside them, that forces you to represent symbolically even the "do nothing" implementation. Analogously 0 seen as a quantity of something, is a symbol for the absence of quantity. Actually in Algebra both 0 and id are considered the neutral elements of the operations + and ∘ (function composition) respectively, or more formally:
for all x of type number:
0 + x = x
x + 0 = x
for all f of type function:
id ∘ f = f
f ∘ id = f
I can also help improve your golf score. Instead of using
($)
you can save a single character by using id.
e.g.
zipWith id [(+1), succ] [2,3,4]
An interesting, more than useful result.
Whenever you need to have a function somewhere, but want to do more than just hold its place (with 'undefined' as an example).
It's also useful, as (soon-to-be) Dr. Stewart mentioned above, for when you need to pass a function as an argument to another function:
join = (>>= id)
or as the result of a function:
let f = id in f 10
(presumably, you will edit the above function later to do something more "interesting"... ;)
As others have mentioned, id is a wonderful place-holder for when you need a function somewhere.
I'm trying to pass a list to a function in Lisp, and change the contents of that list within the function without affecting the original list. I've read that Lisp is pass-by-value, and it's true, but there is something else going on that I don't quite understand. For example, this code works as expected:
(defun test ()
(setf original '(a b c))
(modify original)
(print original))
(defun modify (n)
(setf n '(x y z))
n)
If you call (test), it prints (a b c) even though (modify) returns (x y z).
However, it doesn't work that way if you try to change just part of the list. I assume this has something to do with lists that have the same content being the same in memory everywhere or something like that? Here is an example:
(defun test ()
(setf original '(a b c))
(modify original)
(print original))
(defun modify (n)
(setf (first n) 'x)
n)
Then (test) prints (x b c). So how do I change some elements of a list parameter in a function, as if that list was local to that function?
Lisp lists are based on cons cells. Variables are like pointers to cons cells (or other Lisp objects). Changing a variable will not change other variables. Changing cons cells will be visible in all places where there are references to those cons cells.
A good book is Touretzky, Common Lisp: A Gentle Introduction to Symbolic Computation.
There is also software that draws trees of lists and cons cells.
If you pass a list to a function like this:
(modify (list 1 2 3))
Then you have three different ways to use the list:
destructive modification of cons cells
(defun modify (list)
(setf (first list) 'foo)) ; This sets the CAR of the first cons cell to 'foo .
structure sharing
(defun modify (list)
(cons 'bar (rest list)))
Above returns a list that shares structure with the passed in list: the rest elements are the same in both lists.
copying
(defun modify (list)
(cons 'baz (copy-list (rest list))))
Above function BAZ is similar to BAR, but no list cells are shared, since the list is copied.
Needless to say that destructive modification often should be avoided, unless there is a real reason to do it (like saving memory when it is worth it).
Notes:
never destructively modify literal constant lists
Dont' do: (let ((l '(a b c))) (setf (first l) 'bar))
Reason: the list may be write protected, or may be shared with other lists (arranged by the compiler), etc.
Also:
Introduce variables
like this
(let ((original (list 'a 'b 'c)))
(setf (first original) 'bar))
or like this
(defun foo (original-list)
(setf (first original-list) 'bar))
never SETF an undefined variable.
SETF modifies a place. n can be a place. The first element of the list n points to can also be a place.
In both cases, the list held by original is passed to modify as its parameter n. This means that both original in the function test and n in the function modify now hold the same list, which means that both original and n now point to its first element.
After SETF modifies n in the first case, it no longer points to that list but to a new list. The list pointed to by original is unaffected. The new list is then returned by modify, but since this value is not assigned to anything, it fades out of existence and will soon be garbage collected.
In the second case, SETF modifies not n, but the first element of the list n points to. This is the same list original points to, so, afterwards, you can see the modified list also through this variable.
In order to copy a list, use COPY-LIST.
it's nearly the same as this example in C:
void modify1(char *p) {
p = "hi";
}
void modify2(char *p) {
p[0] = 'h';
}
in both cases a pointer is passed, if you change the pointer, you're changing the parameter copy of the pointer value (that it's on the stack), if you change the contents, you're changing the value of whatever object was pointed.
You probably have problems because even though Lisp is pass-by-value references to objects are passed, like in Java or Python. Your cons cells contain references which you modify, so you modify both original and local one.
IMO, you should try to write functions in a more functional style to avoid such problems. Even though Common Lisp is multi-paradigm a functional style is a more appropriate way.
(defun modify (n)
(cons 'x (cdr n))