Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
user2666425 Avatar asked Feb 15 '23 15:02

user2666425


1 Answers

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).

like image 134
Matt Bryant Avatar answered May 19 '23 00:05

Matt Bryant