user2666425
user2666425

Reputation: 1691

Defining a function in Haskell that returns true if it is the list consisting of 'a', false otherwise

I'm new to Haskell, and I'm trying to write a function that takes a list and returns a bool.

It will return True if its input list is the list consisting of 'a' only, and False otherwise.

This is my best guess:

f :: [a] -> Bool

f ('a':[]) = True

f (x:xs) = False

This fails to compile and returns:

Couldn't match type `a' with `Char'
  `a' is a rigid type variable bound by
      the type signature for f :: [a] -> Bool at charf.hs:6:1
In the pattern: 'b'
In the pattern: 'b' : []
In an equation for `f': f ('b' : []) = True

What is the error in my logic?

Upvotes: 4

Views: 4708

Answers (3)

Daiwen
Daiwen

Reputation: 727

You could also use the function elem, defined in Data.List, to do that.

Here is the documentation link:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v:elem
(if you want to see how it is implemented you can click on source at the end of the line)

f :: [Char] -> Bool
f = elem 'a'

Concerning your answer regarding the type of map. As you said:
map :: (a -> b) -> [a] -> [b]
and
toUpper :: Char -> Char

consequently
map toUpper :: [Char] -> [Char]

if you were to define a function g :: String -> Int then
map g :: [String] -> [Int]
as you see, depending on the function you give as the first argument of map the resulting function may or may not have the same type in input and output.

Upvotes: 0

Lee
Lee

Reputation: 144176

If you want to create a function to test if a list contains a single given value, you need to make some changes.

Firstly you need to provide the expected value to compare against. At the moment you are trying to compare against the Char 'a', but you can't compare a Char to some unknown type a. Secondly, this type needs to be an instance of the Eq class so you can do the comparison.

You can pattern match against a singleton list, and then add a clause to compare the element with the one you expect e.g.

isSingletonOf :: Eq a => a -> [a] -> Bool
isSingletonOf v [s] | v == s = True
isSingletonOf _ _ = False

Then you can create a function to compare [Char]:

f :: [Char] -> Bool
f = isSingletonOf 'a'

Upvotes: 1

Matt Bryant
Matt Bryant

Reputation: 4961

f :: [Char] -> Bool
f ['a'] = True
f _ = False

Use pattern matching. Your function doesn't seem to handle the empty list. Additionally, your function cannot be generic like you want because it clearly takes a [Char] (or a String).

Upvotes: 7

Related Questions