Haskell Function Definition

I'm starting to learn Haskell with "Learn You a Haskell for Great Good!". and I made a strange mistake, and I can’t find the reason.

Here is the code I typed:

let xs = [if x < 3 then "bang" else "boom" | x <- xs]

And the error text in GHCi:

No instance for (Num [Char])
arising from the literal `3'
Possible fix: add an instance declaration for (Num [Char])
In the second argument of `(<)', namely `(3)'
In the expression: x < (3)
In the expression: if x < (3) then "bang" else "boom"

But when I type:

let boom xs = [if x < 3 then "bang" else "boom" | x <- xs]

which is an example of a book, I have no problem.

Can someone explain my mistake?

+5
source share
3 answers

Try specifying a type expression.

xs = [if x < 3 then "bang" else "boom" | x <- xs]

So, xsthis is a list, we still do not know what type of elements it has, so let's look at the following. List items

if x < 3 then "bang" else "boom"

which is an expression of type String(aka [Char]).

So xs :: [String]. x , , xs, String

if x < 3

3 ,

3 :: Num a => a

, x < 3

  • a Num ,
  • String , x String s.

, Num String, .

, Num String ( ?), .

xs - ,

boom xs = [if x < 3 then "bang" else "boom" | x <- xs]

, x String, .

+7

xs , .. xs . , .

"bang" "boom" , Haskell , xs ( xs ). , x xs (x <- xs), x (a.k.a. [Char]). x < 3, , x . , " ".

+13
let xs = ... 

, xs "bang" s / "boom" s, , < 3, , .

let boom xs =...

equates the "arrow" function to the right side of the equation, where the "xs" parameter is the list from which the items to be checked for <3 are drawn.

0
source

All Articles