Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<interactive>:1:1: error: Variable not in scope

Tags:

haskell

I have defined the following function (taken from http://www.happylearnhaskelltutorial.com/1/shop_for_food_with_list.html#s9) on an emacs file:

firstOnesOrEmpty :: [String] -> String
firstOnesOrEmpty [] = ""
firstOnesOrEmpty [x] = x
firstOnesOrEmpty (x:y:_) = x ++ ", " ++ y

But when I load my file onto GHCi and write :t firstOnesOrEmpty into GHCi, I get the following error:

<interactive>:1:1: error: Variable not in scope: firstOnesOrEmpty 

What is going wrong?

I also have a similar problem with another function defined on my emacs file (again from the website above):

joinedWithCommas :: [String] -> String
joinedWithCommas []     = ""
joinedWithCommas [x]    = x
joinedWithCommas (x:xs) = x ++ ", " ++ joinedWithCommas xs

Trying to use this function in GHCi I get:

  "ghci>" joinedWithCommas [] 

  <interactive>:40:1: error:
  Variable not in scope: joinedWithCommas :: [a0] -> t
  "ghci>" joinedWithCommas [x] 

  <interactive>:41:1: error:
  Variable not in scope: joinedWithCommas :: [a0] -> t

  <interactive>:41:19: error: Variable not in scope: x
  "ghci>" joinedWithCommas ["x"] 

  <interactive>:42:1: error:
  Variable not in scope: joinedWithCommas :: [[Char]] -> t

I hope someone can help.

I have looked at previous answers to questions on this topic, and am unable to see how they provide answers to my question.

If someone could point me in the direction of a previous relevant answer and explain how that answer actually answers my question (which I repeat, is not clear to me), I would be extremely grateful.

like image 477
user65526 Avatar asked Jan 02 '23 16:01

user65526


1 Answers

To type a multiline definition in GHCi, you need to enclose it in :{...:}

Prelude> :{
Prelude| joinedWithCommas :: [String] -> String
Prelude| joinedWithCommas []     = ""
Prelude| joinedWithCommas [x]    = x
Prelude| joinedWithCommas (x:xs) = x ++ ", " ++ joinedWithCommas xs
Prelude| :}
Prelude> joinedWithCommas []
""

Otherwise, each line is processed in isolation.

like image 82
chepner Avatar answered Jan 11 '23 09:01

chepner