How to check if all the element in the list of one algebraic type in Haskell? - haskell

If I have following algebraic data type
type MyVal = Either String Int
and have a list containing element of type MyVal
ls = [Right 1, Right 2, Right 3]
xs = [Right 1, Left "error", Right 3]
now, I want write function to find out that is my list having all the value of 'Right' then it should return True otherwise False.
In case of ls it will return True and for xs it will return False.
How can I do that?
I have tried using all function but could not able to use it correctly.

Not to gainsay all isRight as a good answer to the question which was asked, I'd question the question, to some extent. What good is it to compute, as a Bool, whether all the Either values in a list are Right? What does it enable you to do? One answer is that it entitles you to strip the Right tags from the entire list, treating the whole as error free.
A more informative option might be to construct something of type
[Either String Int] -> Either String [Int]
so that instead of a mere True or False, you obtain all the Ints untagged or the message associated with the first pesky Left.
And there is a standard function which does this (and many other things besides). It exploits the fact that lists are a data structure with a standard traversal pattern and that Either String encodes a notion of error-managing computation with standard patterns of failure and success propagation. The type has already done the hard work. All you need to say is...
sequenceA

You can make use of the isRight :: Either a b -> Bool function to check if an Either a b value is a Right x.
So you can implement this with:
import Data.Either(isRight)
allRight :: Foldable f => f (Either a b) -> Bool
allRight = all isRight
This gives us the expected output:
Prelude Data.Either> allRight ls
True
Prelude Data.Either> allRight xs
False

Related

Haskell taking in two list with a int and returning a tuple

I am trying to learn haskell and saw a exercise which says
Write two different Haskell functions having the same type:
[a] -> [b] -> Int -> (a,b)
So from my understanding the expressions should take in two lists, an int and return a tuple of the type of the lists.
What i tried so far was
together :: [a] -> [b] -> Int -> (a,b)
together [] [] 0 = (0,0)
together [b] [a] x = if x == a | b then (b,a) else (0,0)
I know I am way off but any help is appreciated!
First you need to make your mind up what the function should return. That is partly determined by the signature. But still you can come up with a lot of functions that return different things, but have the same signature.
Here one of the most straightforward functions is probably to return the elements that are placed on the index determined by the third parameter.
It makes no sense to return (0,0), since a and b are not per se numerical types. Furthermore if x == a | b is not semantically valid. You can write this as x == a || x == b, but this will not work, since a and b are not per se Ints.
We can implement a function that returns the heads of the two lists in case the index is 0. In case the index is negative, or at least one of the two lists is exhausted, then we can raise an error. I leave it as an exercise what to do in case the index is greater than 0:
together :: [a] -> [b] -> Int -> (a,b)
together [] _ = error "List exhausted"
together _ [] = error "List exhausted"
together (a:_) (b:_) 0 = (a, b)
together (a:_) (b:_) n | n < 0 = error "Negative index!"
| …
you thus still need to fill in the ….
I generally dislike those "write any function with this signature"-type excercises precisely because of how arbitrary they are. You're supposed to figure out a definition that would make sense for that particular signature and implement it. In a lot of cases, you can wing it by ignoring as many arguments as possible:
fa :: [a] -> [b] -> Int -> (a,b)
fa (a:_) (b:_) _ = (a,b)
fa _ _ _ = error "Unfortunately, this function can't be made total because lists can be empty"
The error here is the important bit to note. You attempted to go around that problem by returning 0s, but this will only work when 0 is a valid value for types of a and b. Your next idea could be some sort of a "Default" value, but not every type has such a concept. The key observation is that without any knowledge about a type, in order to produce a value from a function, you need to get this value from somewhere else first*.
If you actually wanted a more sensible definition, you'd need to think up a use for that Int parameter; maybe it's the nth element from each
list? With the help of take :: Int -> [a] -> [a] and head :: [a] -> a this should be doable as an excercise.
Again, your idea of comparing x with a won't work for all types; not every type is comparable with an Int. You might think that this would make generic functions awfully limited; that's the point where you typically learn about how to express certain expectations about the types you get, which will allow you to operate only on certain subsets of all possible types.
* That's also the reason why id :: a -> a has only one possible implementation.
Write two different Haskell functions having the same type:
[a] -> [b] -> Int -> (a,b)
As Willem and Bartek have pointed out, there's a lot of gibberish functions that have this type.
Bartek took the approach of picking two based on what the simplest functions with that type could look like. One was a function that did nothing but throw an error. And one was picking the first element of each list, hoping they were not empty and failing otherwise. This is a somewhat theoretical approach, since you probably don't ever want to use those functions in practice.
Willem took the approach of suggesting an actually useful function with that type and proceeded to explore how to exhaust the possible patterns of such a function: For lists, match the empty list [] and the non-empty list a:_, and for integers, match some stopping point, 0 and some categories n < 0 and ….
A question that arises to me is if there is any other equally useful function with this type signature, or if a second function would necessarily have to be hypothetically constructed. It would seem natural that the Int argument has some relation to the positions of elements in [a] and [b], since they are also integers, especially because a pair of single (a,b) is returned.
But the only remotely useful functions (in the sense of not being completely silly) that I can think of are small variations of this: For example, the Int could be the position from the end rather than from the beginning, or if there's not enough elements in one of the lists, it could default to the last element of a list rather than an error. Neither of these are very pleasing to make ("from the end" conflicts with the list being potentially infinite, and having a fall-back to the last element of a list conflicts with the fact that lists don't necessarily have a last element), so it is tempting to go with Bartek's approach of writing the simplest useless function as the second one.

Check if tuple or triple in haskell

Is there a way to check how many elements (,) has? I know I can access first and second element of a tuple with fst and snd but and thought I could somehow sum elements and then compare it with fst tuple snd tuple and check like this:
tuple = (1,2)
sum tuple == fst tuple + snd tuple
and then I get True for this case and get False for triple = (1,2,3). Eitherway I cant ask fst (1,2,3) nor I can do sum tuple
Is there a way to check if I have a tuple or not?
Something like this:
is_tuple :: (a,b) -> a
is_tuple (a,_) = a
but to get True when I input tuple and False when I give (1,2,3) or (1,2,3,4) and so on... as a input.
i.e:
is_tuple :: Tuple -> Bool
is_tuple x = if x is Tuple
then True
else False
?
Is there a way to check how many elements (,) has?
No, because the answer is always 2.
The type (,) is the type constructor for a tuple of two values, or a 2-tuple. It is a distinct type from (,,), the constructor for 3-tuples. Likewise, both those types are distinct from (,,,), the constructor for 4-tuples, and so on.
When you write a function with type (Foo, Bar) -> Baz, the typechecker will reject any attempts to call the function with a tuple of a different number of values (or something that isn’t a tuple at all). Therefore, your isTuple function only has one logical implementation,
isTuple :: (a, b) -> Bool
isTuple _ = True
…since it is impossible to ever actually call isTuple with a value that is not a 2-tuple.
Without using typeclasses, it is impossible in Haskell to write a function that accepts a tuple of arbitrary size; that is, you cannot be polymorphic over the size of a tuple. This is because, unlike lists, tuples are heterogenous—they can contain values of different types. A function that accepts a tuple of varying length would have no way to predict which elements of the tuple are of which type, and therefore it wouldn’t be able to actually do anything useful.
Very rarely, when doing advanced, type-level trickery, it can be useful to have a type that represents a tuple of varying length, which in Haskell is frequently known as an HList (for heterogenous list). These can be implemented as a library using fancy typeclass machinery and type-level programming. However, if you are a beginner, this is definitely not what you want.
It is difficult to actually give advice on what you should do because, as a commenter points out, your question reads like an XY problem. Consider asking a different question that gives a little more context about the problem you were actually trying to solve that made you want to find the list of a tuple in the first place, and you’ll most likely get more helpful answers.

"For all" statements in Haskell

I'm building comfort going through some Haskell toy problems and I've written the following speck of code
multipOf :: [a] -> (Int, a)
multipOf x = (length x, head x)
gmcompress x = (map multipOf).group $ x
which successfully preforms the following operation
gmcompress [1,1,1,1,2,2,2,3] = [(4,1),(3,2),(1,3)]
Now I want this function to instead of telling me that an element of the set had multiplicity 1, to just leave it alone. So to give the result [(4,1),(3,2),3] instead. It be great if there were a way to say (either during or after turning the list into one of pairs) for all elements of multiplicity 1, leave as just an element; else, pair. My initial, naive, thought was to do the following.
multipOf :: [a] -> (Int, a)
multipOf x = if length x = 1 then head x else (length x, head x)
gmcompress x = (map multipOf).group $ x
BUT this doesn't work. I think because the then and else clauses have different types, and unfortunately you can't piece-wise define the (co)domain of your functions. How might I go about getting past this issue?
BUT this doesn't work. I think because the then and else clauses have different types, and unfortunately you can't piece-wise define the (co)domain of your functions. How might I go about getting past this issue?
Your diagnosis is right; the then and else must have the same type. There's no "getting past this issue," strictly speaking. Whatever solution you adopt has to use same type in both branches of the conditional. One way would be to design a custom data type that encodes the possibilities that you want, and use that instead. Something like this would work:
-- | A 'Run' of #a# is either 'One' #a# or 'Many' of them (with the number
-- as an argument to the 'Many' constructor).
data Run a = One a | Many Int a
But to tell you the truth, I don't think this would really gain you anything. I'd stick to the (Int, a) encoding rather than going to this Run type.

Get elements with odd length in a Haskell list of strings

I have a list of strings in Haskell and I need to get those elements with odd length in another list. How can this be done using higher order functions like foldr, foldl, foldr1, foldl1, filter, map, and so on? I will very much appreciate your help. Can list comprehension be used in this case?
It seems that you are aware that filter exists (since you've mentioned), but perhaps are uncertain how it works. If you're trying to extract a specific subset of a list, this seems to be the right path. If you look at its type-signature, you'll find it's pretty straight-forward:
(a -> Bool) -> [a] -> [a]
That is, it takes a function that returns True or False (i.e. true to contain in the new set, false otherwise) and produces a new list. Similarly, Haskell provides a function called odd in Prelude. It's signature looks as follows:
Integral a => a -> Bool
That is, it can take any Integral type and returns True if it is odd, false otherwise.
Now, let's consider a solution:
filter odd [1..10]
This will extract all the odd numbers between [1,10].
I noticed you mentioned list comprehensions. You probably do not want to use this if you are already given a list and you are simply filtering it. However, a list comprehension would be a perfectly acceptable solution:
[x | x <- [1..10], odd x]
In general, list comprehensions are used to express the generation of lists with more complicated constraints.
Now, to actually answer your question. Since we know we can filter numbers, and if we're using Hoogle searching for the following type (notice that String is simply [Char]):
[a] -> Int
You will see a length function. With some function composition, we can quickly see how to create a function which filters odd length. In summary, we have odd which is type Int -> Bool (in this case) and we have length which is [a] -> Int or-- specifically-- String -> Int. Our solution now looks like this:
filter (odd . length) ["abc","def","eh","123","hm","even"]
Here ya go.
getOddOnes = filter . flip (foldr (const (. not)) id) $ False
Note: if you turn this in for your homework, you'd best be prepared to explain it!

A list of list or a tuple of tuples

I was just wondering if there is a possibility to create a function that returns an (hopefully infinite) list of numbers similar to this. [1, [2, [3, [4]]]].
The closest I got was this.
func list 0 = list
func list num = func newList (num-1)
where newList = list ++ [[num]]
This is used something like this.
func [] 3
Which returns this.
[[3],[2],[1]]
Now I know that this is not infinite nor is it in the correct order but I just wanted to show that I was at least attempting something before posting. :)
Thanks a bunch!
You cannot write such a function, because all elements of a list must have the same type. The list you want to create would not typecheck even in the case of just two elements:
Prelude> :t [1::Int,[2::Int]]
<interactive>:1:9:
Couldn't match expected type `Int' with actual type `[Int]'
In the expression: [2 :: Int]
In the expression: [1 :: Int, [2 :: Int]]
First element is a Int, second one a list of Int, hence typechecking fails.
Although you can express the result with tuples, e.g.
Prelude> :t (1::Int,(2::Int,(3::Int,4::Int)))
(1::Int,(2::Int,(3::Int,4::Int))) :: (Int, (Int, (Int, Int)))
You still cannot write the function, because the type of the result would change depending on the number of elements you wish to have. Let's call f the hypothetical function:
f 1 :: (Int)
f 2 :: (Int,(Int))
f 3 :: (Int,(Int,(Int)))
...
The type of f changes with the argument, so f cannot be written.
The key is to come up with the correct type.
If you want something like [1, [2, [3, [4]]]], then doing exactly that won't work, because all list elements must be the same type.
This makes sense, because when I grab an element out of the list, I need to know what type it is before I can do anything with it (this is sort of the whole point of types, they tell you what you can and can't do with a thing).
But since Haskell's type system is static, I need to know what type it is even without knowing which element of the list it is, because which list index I'm grabbing might not be known until the program runs. So I pretty much have to get the same type of thing whatever index I use.
However, it's possible to do something very much like what you want: you want a data type that might be an integer, or might be a list:
type IntegerOrList a = Either Integer [a]
If you're not familiar with the Either type, a value of Either l r can either be Left x for some x :: l, or Right y for some y :: r. So IntegerOrList a is a type whose values are either an integer or a list of something. So we can make a list of those things: the following is a value of type [IntegerOrList Bool]:
[Left 7, Left 4, Right [True, False], Left 8, Right [], Right [False]]
Okay, so that's one level of lists inside lists, but we can't put lists inside lists inside lists yet – the inner lists contain Bools, which can't be lists. If we instead had [IntegerOrList (IntegerOrList Bool)], we'd be able to have lists inside lists inside lists, but we'd still get no further. In our example, we had a list which contained values which were either integers or lists, and the lists were lists which contained values which were either integers or lists, and... what we really want is something like IntegerOrList (IntegerOrList (IntegerOrList ..., or more simply, something like:
type IntegerOrLists = Either Integer [IntegerOrLists]
But that's not allowed – type synonyms can't be recursive, because that would produce an infinitely large type, which is confusing for the poor compiler. However, proper data types can be recursive:
data IntegerOrLists = I Integer | L [IntegerOrLists]
Now you can build lists like these, mixing integers and lists of your type:
L [I 1, L [I 2, L [I 3, L [I 4]]]]
The key is that whether each item is an integer or a list has to be flagged by using the I or L constructors. Now each element of the list is of type IntegerOrLists, and we can distinguish which it is by looking at that constructor. So the typechecker is happy at last.
{-# LANGUAGE ExistentialQuantification #-}
class Foo a
instance Foo Int
instance Foo [a]
data F = forall a. Foo a => F a
test = F [F (1 :: Int), F [F (2 :: Int), F [F (3 :: Int), F [F (4 :: Int)]]]]
This example shows
That you can have such structures in Haskell, just use some gift wrapping
That these structures are practically useless (try to do something with it)

Resources