Obtaining Values from an Array - list

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

Related

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

"Non-exhaustive patterns" error when summing a list of lists

All I'm trying to do is sum a list of lists. Example of what I want to do:
Input: [[1,2,3],[2,5],[6,7]]
Output: [6,7,13]
The amount of lists inside the outer list can vary, and the amount of integers in each inner list can vary. I've tried a multitude of things, and this is the last one I tried but it doesn't work:
sumSubsets [[x]] = map sum [[x]]
Also, I wanted a base case of sumSubsets [] = [[]] but that causes errors as well. Any help would be appreciated.
You could use
sumSubsets x = map sum x
or even
sumSubsets = map sum
Your previous code,
sumSubsets [[x]] = map sum [[x]]
First performs a pattern match using [[x]] which matches a list containing a single element, which is itself a list containing a single element. Therefore it would work correctly on [[3]]
>> sumSubsets [[3]]
[3]
but not on [[1,2,3]] or [[1],[2]].
I think your problem stems primarily from mixing up types and values, which can happen easily to the beginner, in particular on lists. The whole confusion probably comes from the fact that in Haskell, [] is used as a data constructor as well as a type constructor.
For example, [Int] means "a list of Ints" (a type), but [1] means "the list that contains one element, namely the number 1" (a value -- meaning, the whole list is the value). Both things together:
xs :: [Int]
xs = [1]
When you write polymorphic functions, you abstract from something like the Int. For example, if you want to get the first element of a list, you can define a function that does that for any kind of list -- may they be lists of integers or lists of characters or even lists of lists:
firstElement :: [a] -> a
firstElement (x:xs) = x
[a] means "a list with elements of type a" (a type), and the a alone means "something of type a". firstElement is a function from a list with elements of type a to something of type a. a is a type variable. Since you're not saying what a should be, the function works for all kinds of lists:
*Main> firstElement [1,2,3]
1
*Main> firstElement ['a','b']
'a'
*Main> firstElement [[1,2],[3,4]]
[1,2]
When you wrote [[x]] you were perhaps thinking of the type of the first argument of the function, which would be a list of lists of elements of some type x (x is a type variable). You can still use that, but you have to put it into the type signature of your function (the line that contains the double colon):
sumSubsets :: Num a => [[a]] -> [a]
sumSubsets xs = map sum xs
I've used a here instead of x, since it's more commonly done, but you could use x, too. Unfortunately, the whole thing gets a bit complicated with the Num a which describes additional requirements on the type a (that it belongs to the numbers, since for other things, sum is not defined). To simplify matters, you could write:
sumSubsetsInts :: [[Int]] -> [Int]
sumSubsetsInts xs = map sum xs

SML: How can I pass a function a list and return the list with all negative reals removed?

Here's what I've got so far...
fun positive l1 = positive(l1,[],[])
| positive (l1, p, n) =
if hd(l1) < 0
then positive(tl(l1), p, n # [hd(l1])
else if hd(l1) >= 0
then positive(tl(l1), p # [hd(l1)], n)
else if null (h1(l1))
then p
Yes, this is for my educational purposes. I'm taking an ML class in college and we had to write a program that would return the biggest integer in a list and I want to go above and beyond that to see if I can remove the positives from it as well.
Also, if possible, can anyone point me to a decent ML book or primer? Our class text doesn't explain things well at all.
You fail to mention that your code doesn't type.
Your first function clause just has the variable l1, which is used in the recursive. However here it is used as the first element of the triple, which is given as the argument. This doesn't really go hand in hand with the Hindley–Milner type system that SML uses. This is perhaps better seen by the following informal thoughts:
Lets start by assuming that l1 has the type 'a, and thus the function must take arguments of that type and return something unknown 'a -> .... However on the right hand side you create an argument (l1, [], []) which must have the type 'a * 'b list * 'c list. But since it is passed as an argument to the function, that must also mean that 'a is equal to 'a * 'b list * 'c list, which clearly is not the case.
Clearly this was not your original intent. It seems that your intent was to have a function that takes an list as argument, and then at the same time have a recursive helper function, which takes two extra accumulation arguments, namely a list of positive and negative numbers in the original list.
To do this, you at least need to give your helper function another name, such that its definition won't rebind the definition of the original function.
Then you have some options, as to which scope this helper function should be in. In general if it doesn't make any sense to be calling this helper function other than from the "main" function, then it should not be places in a scope outside the "main" function. This can be done using a let binding like this:
fun positive xs =
let
fun positive' ys p n = ...
in
positive' xs [] []
end
This way the helper function positives' can't be called outside of the positive function.
With this take care of there are some more issues with your original code.
Since you are only returning the list of positive integers, there is no need to keep track of the
negative ones.
You should be using pattern matching to decompose the list elements. This way you eliminate the
use of taking the head and tail of the list, and also the need to verify whether there actually is
a head and tail in the list.
fun foo [] = ... (* input list is empty *)
| foo (x::xs) = ... (* x is now the head, and xs is the tail *)
You should not use the append operator (#), whenever you can avoid it (which you always can).
The problem is that it has a terrible running time when you have a huge list on the left hand
side and a small list on the right hand side (which is often the case for the right hand side, as
it is mostly used to append a single element). Thus it should in general be considered bad
practice to use it.
However there exists a very simple solution to this, which is to always concatenate the element
in front of the list (constructing the list in reverse order), and then just reversing the list
when returning it as the last thing (making it in expected order):
fun foo [] acc = rev acc
| foo (x::xs) acc = foo xs (x::acc)
Given these small notes, we end up with a function that looks something like this
fun positive xs =
let
fun positive' [] p = rev p
| positive' (y::ys) p =
if y < 0 then
positive' ys p
else
positive' ys (y :: p)
in
positive' xs []
end
Have you learned about List.filter? It might be appropriate here - it takes a function (which is a predicate) of type 'a -> bool and a list of type 'a list, and returns a list consisting of only the elements for which the predicate evaluates to true. For example:
List.filter (fn x => Real.>= (x, 0.0)) [1.0, 4.5, ~3.4, 42.0, ~9.0]
Your existing code won't work because you're comparing to integers using the intversion of <. The code hd(l1) < 0 will work over a list of int, not a list of real. Numeric literals are not automatically coerced by Standard ML. One must explicitly write 0.0, and use Real.< (hd(l1), 0.0) for your test.
If you don't want to use filter from the standard library, you could consider how one might implement filter yourself. Here's one way:
fun filter f [] = []
| filter f (h::t) =
if f h
then h :: filter f t
else filter f t

Define a remove function

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.

What does :: and ' mean in oCaml?

What doesx :: xs' mean?
I dont have much functional experience but IIRC in F# 1 :: 2 :: 3 :: [];; creates an array of [1,2,3]
so what does the ' do?
let rec sum xs =
match xs with
| [] -> 0
| x :: xs' -> x + sum xs'
I think sepp2k already answered most of the question, but I'd like to add a couple of points that may clarify how F#/OCaml compiler interprets the code and explain some common uses.
Regarding the ' symbol - this is just a part of a name (a valid identifier starts with a letter and then contains one or more letters, numbers or ' symbols). It is usually used if you have a function or value that is very similar to some other, but is in some way new or modified.
In your example, xs is a list that should be summed and the pattern matching decomposes the list and gives you a new list (without the first element) that you need to sum, so it is called xs'
Another frequent use is when declaring a local utility function that implements the functionality and takes an additional parameter (typically, when writing tail-recursive code):
let sum list =
let rec sum' list res =
match list with
| [] -> res
| x::xs -> sum' xs (res + x)
sum' list 0
However, I think there is usually a better name for the function/value, so I try to avoid using ' when writing code (I think it isn't particularly readable and moreover, it doesn't colorize correctly on StackOverflow!)
Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list (1::[2;3] creates a list [1;2;3]). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.
When creating a list, you use it as an operator that constructs a list (just like when you use + to add two numbers). However, when you use it in the match construct, it is used as a pattern, which is a different syntactic category - the pattern is used to decompose the list into an element and the remainder and it succeeds for any non-empty list:
// operator
let x = 0
let xs = [1;2;3]
let list = x::xs
// pattern
match list with
| y::ys -> // ...
The ' is simply part of the variable name. And yes foo :: bar, where foo is an element of type a and bar is a list of type a, means "the list that has foo as its first element, followed by the elements of bar". So the meaning of the match statement is:
If xs is the empty list, the value is 0. If xs is the list containing the item x followed by the items in xs' the value is x + sum xs'. Since x and xs' are fresh variables, this has the effect that for any non empty list, x will be assigned the value of the first element and xs' will be assigned the list containing all other elements.
Like others have said, the ' is a carryover from mathematics where x' would be said as "x prime"
It's idiomatic in ML-family languages to name a variable foo' to indicate that it's somewhat related to another variable foo, especially in recursions like your code sample. Just like in imperative languages you use i, j for loop indices. This naming convention may be a little surprising since ' is typically an illegal symbol for identifiers in C-like languages.
What does x :: xs' mean?
If you have two variables called x and xs' then x :: xs' creates a new list with x prepended onto the front of xs'.
I dont have much functional experience but IIRC in F# 1 :: 2 :: 3 :: [];; creates an array of [1,2,3]
Not quite. It's a list.
so what does the ' do?
It is treated as an alphabetical character, so the following is equivalent:
let rec sum xs =
match xs with
| [] -> 0
| x :: ys -> x + sum ys
Note that :: is technically a type constructor which is why you can use it in both patterns and expressions.