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

I am new to Haskell and I am trying to write a function that takes a list and returns a bool.

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

This is my best guess:

 f :: [a] -> Bool f ('a':[]) = True f (x:xs) = False 

This does not compile and does not return:

 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?

+4
source share
3 answers
 f :: [Char] -> Bool f ['a'] = True f _ = False 

Use pattern matching. Your function does not seem to process an empty list. Also, your function cannot be as generic as you want, because it explicitly accepts [Char] (or a String ).

+7
source

If you want to create a function to check if the list contains one given value, you need to make some changes.

First, you need to provide the expected value for comparison. You are currently trying to compare with Char 'a', but you cannot compare Char with an unknown type a . Secondly, this type must be an instance of the Eq , so you can do the comparison.

You can map the template to a single list, and then add a sentence to compare the item with the one you expect, for example.

 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' 
+1
source

You can also use the elem function defined in Data.List to do this.

Here is the link to the documentation:
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 the source at the end of the line)

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

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

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

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

0
source

Source: https://habr.com/ru/post/1496342/


All Articles