This is my code im trying to check if a list can be paritially identical into another. It is a game of dominoes a Domino=(Int,Int) and a Board = [Domino] and an end either left or right. I'm to check if any domino goes into a board say for example can domino (2,3) go into board [(3,4)(5,6)] is should be able to go to the left end because (2,3) and (3,4) have have a similar element. Here is my code
goesP :: Domino -> Board -> End -> Bool
goesP (h,t) [(h1,t1)] LeftEnd
| h==h1 || t==h1 =True
| otherwise False
goesP (h,t) [(h1,t1)] RightEnd
| h==t1 || t==t1 = True
| otherwise False
The pattern-matching you're using for the board is incomplete. The [(h1,t1)] pattern will only match Boards with one element (a pair (h1,t1)).
This is the same as using the pattern (h1,t1):[], ie. a list (:) containing the element (h1,t1) followed by an empty list [].
If we try to run your code with the examples you gave, (2,3) and [(3,4), (5,6)] (NOTE: you need a comma between the list elements!) we will get the following:
goesP (2,3) [(3,4), (5,6)] LeftEnd
Haskell will try to match these arguments against the patterns in your definition, from top to bottom.
It will check the following pattern first:
goesP (h,t) [(h1,t1)] LeftEnd
The first and third arguments will match, by 'unifying' h with 2, t with 3 and LeftEnd with LeftEnd, but the second will fail to match. The argument [(3,4), (5,6)] is 'syntactic sugar' for the list (3,4):(5,6):[], whilst the pattern [(h1,t1)] is syntactic sugar for the list (h1,t1):[]. We could unify h1 with 3 and t1 with 4, but there's nothing to unify (5,6) with.
Haskell will move on to the next possibility:
goesP (h,t) [(h1,t1)] RightEnd
The first argument will match (with h as 2 and t as 3), but the second argument will fail for the same reason as the previous clause. The third argument will also fail to match, since LeftEnd and RightEnd are different values (but that's the point ;) ).
Haskell will then see that there are no more possibilities, so the program will crash.
To fix this, you need to change the patterns for the second arguments so that Boards with more than one Domino are handled properly.
The case for LeftEnd is quite easy, just change the list of one element (h1,t1):[] to a list of at least one element (h1,t1):_ (I also added the extra = after otherwise):
goesP (h,t) ((h1,t1):_) LeftEnd
| h==h1 || t==h1 = True
| otherwise = False
The case for RightEnd is harder, since we want to compare with the last element of the list, but we only have access to the first. In this case, we can keep your definition which checks single-element lists, but also add another definition which uses recursion: if the list has more than one element, remove the first element and check it again. That way, any non-empty list will eventually be broken down until it only has one element, which your existing pattern can work with (again, I've added a missing =):
goesP (h,t) [(h1,t1)] RightEnd
| h==h1 || t==h1 = True
| otherwise = False
goesP (h, t) (_:xs) RightEnd = goesP (h, t) xs RightEnd
Now Haskell will match [(3,4), (5,6)] (which is sugar for (3,4):(5,6):[]) against (h1,t1):[]. This will fail, since the lists have different lengths. It will then match [(3,4), (5,6)] against _:xs, which will succeed, unifying xs with (5,6):[]. We then run the function again, using xs. This time the (5:6):[] will unify with the (h1,t1):[], so we can check whether the numbers are equal or not.
Also, an observation: goesP is actually overly complicated. You're using "pattern guards" to choose between the value True and the value False; however, pattern guards also require a Bool to work with. In other words, code like this:
| h==h1 || t==h1 = True
| otherwise = False
Can be read as saying "Create the Bool value h==h1 || t==h1; if it is True, then return True. If it is False then return False."
Clearly this is redundant: we can just return the value h==h1 || t==h1:
goesP (h,t) ((h1,t1):_) LeftEnd = h==h1 || t==h1
goesP (h,t) [(h1,t1)] RightEnd = h==h1 || t==h1
goesP (h, t) (_:xs) RightEnd = goesP (h, t) xs RightEnd
UPDATE: Fixed my RightEnd code
Related
I need to implement the find function, which retrieves the value associated with a particular key from a list of key-value pairs belongs to. The key value pairs are defined by simple tuples.
Example:
find 2 [(3,"xy"),(2,"abc"),(4,"qwe")] == "abc"
find 42 [(1,2),(3,4),(42,42)] == 42
My code:
find :: Eq a => a -> [(a, b)] -> b
find 'x (a, b)
| x == a = b
find :: Eq a => a -> [(a, b)] -> Maybe b
find _ [] = Nothing
find x ((a, b):xs)
| x == a = Just b
| otherwise = find x xs
I took the liberty to change the return type of the function signature to Maybe b to cover the case when the searched value is not found. That's customary in these situations in Haskell, as far as I know.
There are 2 basic patterns. If the list is exhausted and no result was found previously, return Nothing. Otherwise, check if it's a match, if so return the value wrapped in Just, otherwise recurse further searching.
I am looking at Haskell elemIndex function:
elemIndex :: Eq a => a -> [a] -> Maybe Int
What does Maybe mean in this definition? Sometimes when I call it, the output has a Just or a Nothing What does it mean? How can I interpret this if I were to use folds?
First question:
What does it mean?
This means that the returned value is either an index (Int) or Nothing.
from the docs:
The elemIndex function returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element.
The second question:
How can I interpret this if I were to use folds?
I'm not sure there is enough context to the "were to use folds" part. But, there are at least 2 ways to use this function:
case analysis, were you state what to return in each case:
case elemIndex xs of
Just x -> f x -- apply function f to x.
Nothing -> undefined -- do something here, e.g. give a default value.
use function maybe:
maybe defaultValue f (elemIndex xs)
Maybe is a sum type.
Sum type is any type that has multiple possible representations.
For example:
data Bool = False | True
Bool can represented as True or False. The same goes with Maybe.
data Maybe a = Nothing | Just a
The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), or it is empty (represented as Nothing)
elemIndex :: Eq a => a -> [a] -> Maybe Int
The elemIndex function returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element.
Lets compare it to the indexOf function
What are the possible values of this method?
The index of the element in the array in case it was found (lets say 2).
-1 in case it was not found.
Another way to represent it:
Return a number in case it was found - Just 2.
Instead of returning magic numbers like -1 we can return a value that represents the
option of a failure - Nothing.
Regarding "How can I interpret this if I were to use folds", I do not have enough information to understand the question.
Maybe is a type constructor.
Int is a type. Maybe Int is a type.
String is a type. Maybe String is a type.
For any type a, Maybe a is a type. Its values come in two varieties: either Nothing or Just x where x is a value of type a (we write: x :: a):
x :: a
----------------- ------------------
Just x :: Maybe a Nothing :: Maybe a
In the first rule, the a in both the type of the value x :: a and the type of the value Just x :: Maybe a is the same. Thus if we know the type of x we know the type of Just x; and vice versa.
In the second rule, nothing in the value Nothing itself determines the a in its type. The determination will be made according to how that value is used, i.e. from the context of its usage, from its call site.
As to the fold implementation of elemIndex, it could be for example
elemIndex_asFold :: Eq a => a -> [a] -> Maybe Int
elemIndex_asFold x0 = foldr g Nothing
where
g x r | x == x0 = Just x
| else = r
Imagine I have a custom type and two functions:
type MyType = Int -> Bool
f1 :: MyType -> Int
f3 :: MyType -> MyType -> MyType
I tried to pattern match as follows:
f1 (f3 a b i) = 1
But it failed with error: Parse error in pattern: f1. What is the proper way to do the above?? Basically, I want to know how many f3 is there (as a and b maybe f3 or some other functions).
You can't pattern match on a function. For (almost) any given function, there are an infinite number of ways to define the same function. And it turns out to be mathematically impossible for a computer to always be able to say whether a given definition expresses the same function as another definition. This also means that Haskell would be unable to reliably tell whether a function matches a pattern; so the language simply doesn't allow it.
A pattern must be either a single variable or a constructor applied to some other patterns. Remembering that constructor start with upper case letters and variables start with lower case letters, your pattern f3 a n i is invalid; the "head" of the pattern f3 is a variable, but it's also applied to a, n, and i. That's the error message you're getting.
Since functions don't have constructors, it follows that the only pattern that can match a function is a single variable; that matches all functions (of the right type to be passed to the pattern, anyway). That's how Haskell enforces the "no pattern matching against functions" rule. Basically, in a higher order function there's no way to tell anything at all about the function you've been given except to apply it to something and see what it does.
The function f1 has type MyType -> Int. This is equivalent to (Int -> Bool) -> Int. So it takes a single function argument of type Int -> Bool. I would expect an equation for f1 to look like:
f1 f = ...
You don't need to "check" whether it's an Int -> Bool function by pattern matching; the type guarantees that it will be.
You can't tell which one it is; but that's generally the whole point of taking a function as an argument (so that the caller can pick any function they like knowing that you'll use them all the same way).
I'm not sure what you mean by "I want to know how many f3 is there". f1 always receives a single function, and f3 is not a function of the right type to be passed to f1 at all (it's a MyType -> MyType -> MyType, not a MyType).
Once a function has been applied its syntactic form is lost. There is now way, should I provide you 2 + 3 to distinguish what you get from just 5. It could have arisen from 2 + 3, or 3 + 2, or the mere constant 5.
If you need to capture syntactic structure then you need to work with syntactic structure.
data Exp = I Int | Plus Exp Exp
justFive :: Exp
justFive = I 5
twoPlusThree :: Exp
twoPlusThree = I 2 `Plus` I 3
threePlusTwo :: Exp
threePlusTwo = I 2 `Plus` I 3
Here the data type Exp captures numeric expressions and we can pattern match upon them:
isTwoPlusThree :: Exp -> Bool
isTwoPlusThree (Plus (I 2) (I 3)) = True
isTwoPlusThree _ = False
But wait, why am I distinguishing between "constructors" which I can pattern match on and.... "other syntax" which I cannot?
Essentially, constructors are inert. The behavior of Plus x y is... to do nothing at all, to merely remain as a box with two slots called "Plus _ _" and plug the two slots with the values represented by x and y.
On the other hand, function application is the furthest thing from inert! When you apply an expression to a function that function (\x -> ...) replaces the xes within its body with the applied value. This dynamic reduction behavior means that there is no way to get a hold of "function applications". They vanish into thing air as soon as you look at them.
I was doing some haskell programming and had an error when using guards, when i changed guards to 'case of' the problem was gone, and i can't understan why exactly is that happening. I've made a a very simple example of the situation i was in:
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
c1 :: Shape
c1 = Circle (Point 5 5 ) 12
--returns Just True if radius is bigger than 10, otherwise = Nothing
isBigger :: Shape -> Maybe Bool
isBigger (Circle _ x)
|x > 10 = Just True
|otherwise = Nothing
Now, i've made these two functions (Apart from different notation they seem to do exactly the same to me):
first:
printStuff:: Shape -> String
printStuff s1
|isBigger s1 == Just a = show a
|isBigger s1 == Nothing = "Not bigger than 10"
and the second one:
printStuff2:: Shape -> String
printStuff2 s1 =
case isBigger s1 of
Nothing -> "Not Bigger than 10"
Just a -> show a
But, code with with function 'PrintStuff' won't run. Error:
Not in scope: ‘a’
However, second function runs and does its job. Whats the difference between guards and case here?
Guards use boolean expressions, whereas case … of uses pattern matching. So for case, the usual pattern match rules hold. So your second function is (almost) the same as:
printStuff2:: Shape -> String
printStuff2 s1 = helper (isBigger s1)
where
helper Nothing = "Not Bigger than 10"
helper (Just a) = show a
-- ^^^^^^^
-- pattern matching
Now, guards did not pattern match originally (that was introduced by an extensions). They only take expressions of type Bool:
printStuff :: Shape -> String
printStuff s1
| bigger == Nothing = "Not Bigger than 10"
| otherwise = a
where
bigger = isBigger s1
(Just a) = bigger
Note that the last binding can be dangerous if you forget to check whether bigger is actually Just something. However, with PatternGuards, you can use
printStuff :: Shape -> String
printStuff s1
| Just a <- isBigger s1 = show a
| otherwise = "Not Bigger than 10"
That being said, this is a job for maybe:
printStuff :: Shape -> String
printStuff s1 = maybe "Not Bigger than 10" show (isBigger s1)
This question relates to the scala course from coursera so I want to please ask you to not give me the plain solution that I can copy-paste as this would break the coursera honor code.
This relates to the second assignment.
def Set = Int => Boolean
As it can be seen, Set is a function which returns weather or not the given int is or not part of the set. This is plain and simple so far. However the task asks me to create a union
def union(f: Set, s: Set): Set = ???
This union should return a set that satisfies the condition of both sets.
How could I do something like this:
I thought that such a thing could be done by adding the functions together however the following code:
f + s
Will not compile properly as expected
My question to is:
How would I be able to create a function from 2 other functions?
x => if x == 0 true else false //first
x => if x == 1 true else false //second
And what should equal:
x => if x==0 || x == 1 true else false
I'm not asking for a solution but rather how would I go around building something like this?
As I think you already understand, these Sets are functions that test whether a value meets the criteria for each Set.
The union of such a Set must also be a function that returns a Boolean (as shown by the type signature)
def union(f: Set, s: Set): Set
which (because Set is a type alias) is equivalent to:
def union(f: Int => Boolean, s: Int => Boolean): Int => Boolean
In plain English, union of two sets A and B means: "is the item in A or B".
Your task is to write a function that carries out that plain English specification.
You cannot "add" two functions together (at least, not in a way that is applicable to this question), but you can combine their results.
The Set has form of Set = Int => Boolean. Given the Int function will return true if the value is in a Set.
Well if we want to create a singleton set, we will return new function, which will compare any value passed to it, with the one passed to the function that created it.
The union of two sets, is one set plus the other. It means the element you're looking for must be either in one or the other set. But how do we get the new set, well we return a new function that does just that - checks if an element is either in one set or another.
Remember that in Scala functions can return functions, which may be evaluated later. I think that's the key.
The Set is defined as a function from Int to Boolean, "summing" two Sets won't return a Set object, the union means that one element should be either in one or in the other set but always expressed as a function.
I hope this is not too much, but given an element it should satisfy either f or s.
First of all, it's type Set =. Not def. Set is a type alias not a function definition.
Now, your question. You need a function which, when given two Int =>Boolean combines them with OR and returns a Int => Boolean.
First, how would you do this for two Boolean arguments?
def or(a: Boolean, b: Boolean) = a || b
So now we're half way there. What we have:
A pair of Int => Boolean functions.
A function that takes two Booleans and return a Boolean.
So all we need to do is apply each Set to an Int to get a Boolean and OR the result. The confusion is probably here.
The easiest way to curry a function is to do it explicitly
def union(f: Set, s: Set): Set = {
def doUnion(x: Int) = //apply x to f and s, return OR
doUnion
}
But we can, in Scala, so this inline by declaring an anonymous function
def union(f: Set, s: Set): Set = x => //apply x to f and s, return OR