Define a remove function - list

I'm having trouble with this exercise, please help !
Define a function remove that takes an integer and
a list of integers as input and returns the list obtained by deleting
the first occurrence of the integer in the list;
delete :: Int -> [Int] -> [Int]

I'm learning Haskell, so my answer is not authoritative. Rather than posting the code that I've written to answer you question, I try to write the way I looked at the problem.
I approached it looking at the various cases (I've found that this helps with Haskell):
deleting whatever from an empty list ... that's easy
deleting something (x) from a non-empty list (ys):
2.1. is x equal to the first element of ys? then I'm done ...
2.2. otherwise I just have to delete x from the list starting after the first element of ys

Think about delete as building a new list without the element in question, rather than removing the element itself. (sounds like homework so I'll be no more specific than that :))

Sorry to give away the answer, but here it is, straight from the source of Data.List
delete :: (Eq a) => a -> [a] -> [a]
delete = deleteBy (==)
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy _ _ [] = []
deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
Normally I'd describe it here, but if you understand basic recursion, if statements, pattern matching, and the : operator, and partial application/currying, then it should be self-explanatory. Feel free to ask if any one of these is foreign to you.

first: declare the function (look up how function declarations work) - depending on language it looks similar to this:
array
delete( int input1, array input2 )
{
}
then work on the body of the function
declare tha variables you need,
perform the array manipulation
return the resulting array.

Related

Write a function that takes an Integer list as input and adds 5 to each element of the list

I'm fairly new to Haskell and functional programming in general.
This seems like such a simple problem but I'm struggling with the syntax.
I want to take a list of ints as input, if it is null return a null list, and if it is not null then use the map function to add five to every element.
This is my code so far but it produces lots of errors. Any suggestions?
addFive :: [a] -> [a]
addFive [] = []
addFive a = map(+5)
You can use
addFive = map (+5)
or
addFive a = map (+5) a
As map works on empty list, explicit implementation for empty list is not required.
You are thinking along the right lines, but there are a couple of issues.
The code you have shown will complain about a type error. This is because the type of map (+5) is [a] -> [a], but you want just [a]. To fix this you just need to change that line to
addFive a = map (+5) a
Look at the types and think about why this works.
You may also have tried this:
addFive :: [a] -> [a]
addFive [] = []
addFive = map(+5)
This gives you a different error because every version of a function like this needs to have the same number of arguments. Your null case takes one argument, so the other one has to take an argument too.
However you don't need the null case. map already has that built in. So what you actually need is
addFive :: [a] -> [a]
addFive = map (+5)
By the way, one stylistic point. In Haskell we use a, b etc for type variables, but x, xs, y etc for value variables. So the version above would be more idiomatic with
addFive xs = map (+5) xs

Adding values to an ocaml list based on its existing values

I'm learning about the map and fold functions. I'm trying to write a function that takes a list and returns a list with all of the values in the original, each followed by that value's double.
Example: add_dbls [2;5;8] = [2;4;5;10;8;16]
Everything I try results in a list of lists, instead of a list. I'm struggling to come up with a better approach, using either map or fold (or both).
This is what I came up with originally. I understand why this returns a list of lists, but can't figure out how to fix it. Any ideas would be appreciated!
let add_dbls list =
match list with
| h::t -> map (fun a-> [a;(a*2)]) list
| [] -> []
Also, my map function:
let rec map f list =
match list with
| h::t -> (f h)::(map f t)
| [] -> []
You are nearly there. As you have observed, since we get list of lists, we need to flatten it to get a final list. List.concat function does exactly that:
let add_dbls list =
let l =
match list with
| h::t -> List.map (fun a -> [a;(a*2)]) list
| [] -> []
in
List.concat l
Here is the updated function that that computes the output that you require.
Now the output of add_dbls [2;5;8] = [2;4;5;10;8;16].
Although this works, it probably isn't efficient as it allocates a new list per item in your original list. Below are variations of the same function with different characteristics which depend on the size of l.
(* Safe version - no stack overflow exception. Less efficient(time and size) than add_dbls3 below. *)
let add_dbls2 l =
List.fold_left
(fun acc a -> (a*2)::a::acc)
[]
l
|> List.rev
(* Fastest but unsafe - stack overflow exception possible if 'l' is large - fold_right is not tail-recursive. *)
let add_dbls3 l =
List.fold_right
(fun a acc -> a::(a*2)::acc)
l
[]
It's should be simple to see that List.map always returns a list of the same length as the input list. But you want a list that's twice as long. So List.map cannot work for you.
You can solve this using List.fold_left or List.fold_right. If you're still having trouble after you switch to using a fold, you could update your question with the new information.
Update
The type of your fold function (a left fold) is this:
('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
So, the folded function takes an accumulated answer and an element of the list, and it returns a new accumulated answer.
Your folded function is like this:
fun a b -> a::b::(b*2)
It attempts to use the :: operator to add new elements to the end of the accumulated list. But that's not what the :: operator does. It adds an element to the beginning of a list.
There's no particularly nice way to add an element to the end of a list. This is intentional, because it's a slow operation.
When using a left fold, you need to reconcile yourself to building up the result in reverse order and possibly reversing it at the end. Or you can use a right fold (which is generally not tail recursive).

Haskell self-referential List termination

EDIT: see this followup question that simplifies the problem I am trying to identify here, and asks for input on a GHC modification proposal.
So I was trying to write a generic breadth-first search function and came up with the following:
bfs :: (a -> Bool) -> (a -> [a]) -> [a] -> Maybe a
bfs predf expandf xs = find predf bfsList
where bfsList = xs ++ concatMap expandf bfsList
which I thought was pretty elegant, however in the does-not-exist case it blocks forever.
After all the terms have been expanded to [], concatMap will never return another item, so concatMap is blocking waiting for another item from itself? Could Haskell be made smart enough to realize the list generation is blocked reading the self-reference and terminate the list?
The best replacement I've been able to come up with isn't quite as elegant, since I have to handle the termination case myself:
where bfsList = concat.takeWhile (not.null) $ iterate (concatMap expandf) xs
For concrete examples, the first search terminates with success, and the second one blocks:
bfs (==3) (\x -> if x<1 then [] else [x/2, x/5]) [5, 3*2**8]
bfs (==3) (\x -> if x<1 then [] else [x/2, x/5]) [5, 2**8]
Edited to add a note to explain my bfs' solution below.
The way your question is phrased ("could Haskell be made smart enough"), it sounds like you think the correct value for a computation like:
bfs (\x -> False) (\x -> []) []
given your original definition of bfs should be Nothing, and Haskell is just failing to find the correct answer.
However, the correct value for the above computation is bottom. Substituting the definition of bfs (and simplifying the [] ++ expression), the above computation is equal to:
find (\x -> False) bfsList
where bfsList = concatMap (\x -> []) bfsList
Evaluating find requires determining if bfsList is empty or not, so it must be forced to weak head normal form. This forcing requires evaluating the concatMap expression, which also must determine if bfsList is empty or not, forcing it to WHNF. This forcing loop implies bfsList is bottom, and therefore so is find.
Haskell could be smarter in detecting the loop and giving an error, but it would be incorrect to return [].
Ultimately, this is the same thing that happens with:
foo = case foo of [] -> []
which also loops infinitely. Haskell's semantics imply that this case construct must force foo, and forcing foo requires forcing foo, so the result is bottom. It's true that if we considered this definition an equation, then substituting foo = [] would "satisfy" it, but that's not how Haskell semantics work, for the same reason that:
bar = bar
does not have value 1 or "awesome", even though these values satisfy it as an "equation".
So, the answer to your question is, no, this behavior couldn't be changed so as to return an empty list without fundamentally changing Haskell semantics.
Also, as an alternative that looks pretty slick -- even with its explicit termination condition -- maybe consider:
bfs' :: (a -> Bool) -> (a -> [a]) -> [a] -> Maybe a
bfs' predf expandf = look
where look [] = Nothing
look xs = find predf xs <|> look (concatMap expandf xs)
This uses the Alternative instance for Maybe, which is really very straightforward:
Just x <|> ... -- yields `Just x`
Nothing <|> Just y -- yields `Just y`
Nothing <|> Nothing -- yields `Nothing` (doesn't happen above)
so look checks the current set of values xs with find, and if it fails and returns Nothing, it recursively looks in their expansions.
As a silly example that makes the termination condition look less explicit, here's its double-monad (Maybe in implicit Reader) version using listToMaybe as the terminator! (Not recommended in real code.)
bfs'' :: (a -> Bool) -> (a -> [a]) -> [a] -> Maybe a
bfs'' predf expandf = look
where look = listToMaybe *>* find predf *|* (look . concatMap expandf)
(*>*) = liftM2 (>>)
(*|*) = liftM2 (<|>)
infixl 1 *>*
infixl 3 *|*
How does this work? Well, it's a joke. As a hint, the definition of look is the same as:
where look xs = listToMaybe xs >>
(find predf xs <|> look (concatMap expandf xs))
We produce the results list (queue) in steps. On each step we consume what we have produced on the previous step. When the last expansion step added nothing, we stop:
bfs :: (a -> Bool) -> (a -> [a]) -> [a] -> Maybe a
bfs predf expandf xs = find predf queue
where
queue = xs ++ gen (length xs) queue -- start the queue with `xs`, and
gen 0 _ = [] -- when nothing in queue, stop;
gen n q = let next = concatMap expandf (take n q) -- take n elemts from queue,
in next ++ -- process, enqueue the results,
gen (length next) (drop n q) -- advance by `n` and continue
Thus we get
~> bfs (==3) (\x -> if x<1 then [] else [x/2, x/5]) [5, 3*2**8]
Just 3.0
~> bfs (==3) (\x -> if x<1 then [] else [x/2, x/5]) [5, 2**8]
Nothing
One potentially serious flow in this solution is that if any expandf step produces an infinite list of results, it will get stuck calculating its length, totally needlessly so.
In general, just introduce a counter and increment it by the length of solutions produced at each expansion step (length . concatMap expandf or something), decrementing by the amount that was consumed. When it reaches 0, do not attempt to consume anything anymore because there's nothing to consume at that point, and you should instead terminate.
This counter serves in effect as a pointer back into the queue being constructed. A value of n indicates that the place where the next result will be placed is n notches ahead of the place in the list from which the input is taken. 1 thus means that the next result is placed directly after the input value.
The following code can be found in Wikipedia's article about corecursion (search for "corecursive queue"):
data Tree a b = Leaf a | Branch b (Tree a b) (Tree a b)
bftrav :: Tree a b -> [Tree a b]
bftrav tree = queue
where
queue = tree : gen 1 queue -- have one value in queue from the start
gen 0 _ = []
gen len (Leaf _ : s) = gen (len-1) s -- consumed one, produced none
gen len (Branch _ l r : s) = l : r : gen (len+1) s -- consumed one, produced two
This technique is natural in Prolog with top-down list instantiation and logical variables which can be explicitly in a not-yet-set state. See also tailrecursion-modulo-cons.
gen in bfs can be re-written to be more incremental, which is usually a good thing to have:
gen 0 _ = []
gen n (y:ys) = let next = expandf y
in next ++ gen (n - 1 + length next) ys
bfsList is defined recursively, which is not in itself a problem in Haskell. It does, however, produce an infinite list, which, again, isn't in itself a problem, because Haskell is lazily evaluated.
As long as find eventually finds what it's looking for, it's not an issue that there's still an infinity of elements, because at that point evaluation stops (or, rather, moves on to do other things).
AFAICT, the problem in the second case is that the predicate is never matched, so bfsList just keeps producing new elements, and find keeps on looking.
After all the terms have been expanded to [] concatMap will never return another item
Are you sure that's the correct diagnosis? As far as I can tell, with the lambda expressions supplied above, each input element always expand to two new elements - never to []. The list is, however, infinite, so if the predicate goes unmatched, the function will evaluate forever.
Could Haskell be made smart enough to realize the list generation is blocked reading the self-reference and terminate the list?
It'd be nice if there was a general-purpose algorithm to determine whether or not a computation would eventually complete. Alas, as both Turing and Church (independently of each other) proved in 1936, such an algorithm can't exist. This is also known as the Halting problem. I'm not a mathematician, though, so I may be wrong, but I think it applies here as well...
The best replacement I've been able to come up with isn't quite as elegant
Not sure about that one... If I try to use it instead of the other definition of bfsList, it doesn't compile... Still, I don't think the problem is the empty list.

How do you pass list in a function parameter in haskell?

I know this question has been asked previously many times, and I've carefully read them, but it doesn't help me answer my type of question. I'm very new to Haskell,
Lets suppose we have the following:
filter p [] = []
filter p (h:l) = if (p h) then (h:(filter p l)) else (filter p l)
I have two questions
How can I call filter? All I know is that you pass p which is a list
I honestly don't know what is polymorphic type in general, and I cant figure out the polymorphic type of filter function.
I dont event understand what the function filter does in the if statement.
I would really appreciate if you can assist me in these two question.
There's plenty of resources to explain polymorphism, but I don't understand them.
p is not a list. p is short for predicate - usual terminology for a function taking a value and returning Bool. A list is the second argument to filter.
How do you call filter? You need to be reading one of the many haskell books out there. Right now. Some examples:
filter (> 5) [1, 6, 2, 8, 9, 3] -- [6, 8, 9]
filter (== 'z') "bazzz" -- "zzz" (String === [Char])
Here (> 5) :: Int -> Bool and (== 'z') :: Char -> Bool are predicates.
Polymorphic very loosely means it has the same form for different types:
filter :: (a -> Bool) -> [a] -> [a]
filter must work for any type a. The particular a is thus unknown to the implementer and the function cannot assume anything about a. a is chosen by the function user at the call site.
Btw. it's a fun little exercise to figure out what the following function is allowed to do:
:: a -> a
(Hint: there's only one thing it can do, and the name gives it away so I left it out)
You could also think of filter as a family of functions that are implemented exactly the same and only differ in a. Some of those could be:
:: (Int -> Bool) -> [Int] -> [Int]
:: (Char -> Bool) -> [Char] -> [Char]
:: (Foo -> Bool) -> [Foo] -> [Foo]
SO is not really a great place to start when learning new concepts. You should really grab a good book.
Before getting into any details about the implementation, we should settle on what the type of filter should be. Indeed you should generally design the type signature of a function without ever writing any actual code... but the damage is done here already. (As chi remarks, you could at this point actually ask GHCi what the type of your implementation is... but again, that's backwards so I won't delve into it.)
So what do you want filter to accomplish? Indeed it should take a list. You want to extract certain elements of that list depending on some property each of them might have; but filter shouldn't have any hard-baked assumptions what criteria to use, i.e. it should be the type of a list of any type of element. In Haskell, we write this [a] (which is actually shorthand for ∀ a . [a], read this as “for all element-types you might consider – say, A – it's a list of type [A]”).
What the actual criterion is should then be determined by an extra argument: the filtering predicate. For instance, you might want to filter all numbers smaller than 5 from a list of integers – you'd use the predicate (<5) :: Int -> Bool. In general, for your [a] list you need a predicate with the type a -> Bool. The end result would have the same list-elements as you passes in, so then filter would have the signature
filter :: [a] -> (a -> Bool) -> [a]
...except by convention, we put the predicate first, i.e.
filter :: (a -> Bool) -> [a] -> [a]
Let's check this makes sense... we'd want, for instance,
> filter ((<5) :: Int -> Bool) ([4,9,3] :: [Int])
in which case a ~ Int so
filter :: (Int -> Bool) -> [Int] -> [Int]
...yup, that makes sense.
Now you start actually worrying about the implementation. There are two general approaches:
Use some pre-existing combinators from a library to define the function. This is very of preferrable to start dabbling with manual recursion etc., but for now let's do everything by hand.
Deconstruct the list. Basically, there are only two ways a list can look: it can either contain something, or be empty. Empty is easy, because in this case you can't possibly return anything but an empty list again. You can't even use the predicate because there is no element you could check with it, hence just discard it by matching to _:
filter _ [] = []
(Alternatively as you had it, you can also match the predicate as p, but then people will wonder: what happened to the mouse p?)
If the list is not empty, we can straight pop one element from it:
filter p (h:l) = …
here, h is the head element and l is the rest of the list. So great, we now have an element of type a, let's see what the predicate tells us about it!
filter p (h:l) = if p h then … else …
So if the predicate is fulfilled we want to see h again in the final result, won't we? In fact the final result should start with h, thus
filter p (h:l) = if p h then h : … else …
The rest of the final result should have something to do with the rest of the input list. We could pass is as is then h : l else …, but that would mean we would only ever control the condition for the head element. No, we still have to filter the rest of the list as well:
filter p (h:l) = if p h then h : filter p l else …
Indeed we also want to do that even if the predicate is not fulfilled for h, except then we don't prepend it:
filter p (h:l) = if p h then h : filter p l else filter p l
And there you go:
filter _ [] = []
filter p (h:l) = if p h then h : filter p l else filter p l
This if looks a bit clunky, the preferred syntax are actually guards (which do the same thing)
filter _ [] = []
filter p (h:l)
| p h = h : filter p l
| otherwise = filter p l

Obtaining Values from an Array

I am incredibly new to Haskell, and I am having trouble with some homework. I do not understand how to properly take in an array, and use the data with in it.
for example in java I would have something like
int[] arr = {...};
arr[0];
arr[1];
In my Haskell problem I have
dot :: [Float] -> [Float] -> Float
-- enter code here
I can not find a way to use the data inside the float array. My professors example for this problem uses Vectors, but we have to use a [Float]
I'm not asking for anyone to do the problem, just an explanation on how to use the array.
This is technically speaking not an array, but a (linked-)list. That is something different. A list is defined as:
data [a] = [] | (a:[a])
So it is a data-type that has two constructors:
the empty list [] which is used to signal the end of a list; and
the cons that has two elements: an a (the item) and a reference to the tail (a [a]).
Now that we know that you can use pattern matching to extract elements (and do tests). For instance in the following function:
head :: [a] -> a
head (x:_) = x
Here head expects to see a cons construct and it extracts the head (the element of the first node) and returns that. Or for instance:
second :: [a] -> a
second (_:(x:_)) = x
here again you use pattern matching to extract the second element.
Another way to obtain elements is using the (!!) :: [a] -> Int -> a. operator. You can obtain the i-th element (zero-based), by using:
list!!i
which is equivalent to list[i] in Java semantically. Mind however that - as said before - these are linked lists, so obtaining the i-th element requires O(i) computational effort. Although this may look like a detail it can become a bit dramatic when you want to fetch an object with a large index. Furthermore since (!!) is called, you are less certain there is such element: you have not that much guarantees that the list is indeed long enough. It is therefore wise to use pattern matching and look for clever ways to exploit the linked list data structure.
For your example for the dot product, you can for instance first use pattern matching like:
dot (x:xs) (y:ys) = ...
and so you have extracted the heads x and y from the lists. And then you can multiply them and add them to the dot product of the remainder of the list:
dot (x:xs) (y:ys) = x*y + dot xs ys
now you only still need to define base case(s) like for instance:
dot [] [] = 0.0
so putting it all together:
dot :: [Float] -> [Float] -> Float
dot [] [] = 0.0
dot (x:xs) (y:ys) = x*y + dot xs ys