If something is not a list in Haskell

How to check if an object in Haskell is not a list? for example, I want to know if let a = 55, ais a list or just a number?

+5
source share
3 answers

You do not check. You do.

But really, what are you trying to do here?

If you are trying to ensure that your function is only called using a list

Haskell will ensure that your function is called only with a list. If you try to call your function using a non-list, this will result in a compilation error.

eg.

myFunction :: [a] -> String
myFunction []  = "no elements!"
myFunction [_] = "single element!"
myFunction _   = "many elements!"

then

myFunction [42] -- >>> "single element!"
myFunction 42   -- ERROR: not a list

If you want your function to do something sensible, whether it is called by a list or something else

typeclass: , , ( ); Haskell , .

.

class MyClass a
  where myFunction :: a -> String

instance MyClass Int
  where myFunction 0 = "zero!"
        myFunction 1 = "one!"
        myFunction _ = "something!"

instance MyClass a => MyClass [a]
  where myFunction []  = "no elements!"
        myFunction [x] = "only " ++ myFunction x
        myFunction _   = "many elements!"

myFunction [42] -- >>> "only something!"
myFunction 42   -- >>> "something!"

- - .

, , . , .

+25

Haskell , .. , identifier - [Int] Int.

+6

ghci :t (:type):

> let a = 55
> :t a
a :: Integer
> let b = [1..5]
> :t b
b :: [Integer]

, a - Integer, b - Integer.

+4

All Articles