Defining lists in Haskell - list

I'd like to know how to define this as a list within Haskell so that I could perform operations such as tail, reverse and length:
cars = "lamborghinis are my favourite types of car"
I've tried:
let cars = [lamborghinis,are,my,favourite,types,of,car]
let cars = ["lamborghinis","are","my","favourite","types","of","car"]
let cars = ['lamborghinis','are','my','favourite','types','of','car']
I have been using http://learnyouahaskell.com/starting-out as a tutorial as I am new to Haskell and I can't see where I'm going wrong, I thought my first attempt above would be correct as that it how it does it in the tutorial but with numbers instead of words.
The error I am getting is: parse error on input 'of.
Any ideas where I'm going wrong? Thanks.

let cars = "lamborghinis are my favourite types of car"
makes cars a list of characters [Char]==String and head cars should give you the first letter. This is special syntax of haskell for strings
let cars2 = ["lamborghinis","are","my","favourite","types","of","car"]
This is the normal form for defining lists and gives you a list of strings [String] and head cars should give you "lamborghinis".
You can also split a sentance into words using the words function.
let cars3 = words cars

The type String is only a type synonym for [Char].
This means that for example "Hello, you" is the same as ['H','e','l','l','o',',',' ','y','o','u']

Related

Dungeons and Dragons Character Sheet generator using Python

For fun I'm trying to create a character generator sheet for Dungeons and Dragons. I've got the program to randomly roll for my strength, charisma etc.
Now I want to be able to ask the user, "What type of weapon do you want to use?" Get_Weapon_Choice, then pull up a list of that weapon type. I've tried creating a list weapon_Choices = ['Bow', 'Sword', ]. Then I created 2 other lists, bow = ['short', 'long', 'crossbow'] and swords = ['short', 'long'] I know how to get input from the user, but I don't know how to take that input and print the list, I'm printing the variable name.
chooseWeapon = input('What type of weapon would you like? Bow or Sword?')
How do I use chooseWeapon to compare to weapon_Choices to make sure they didn't enter something like Spells, then use chooseWeapon to print either the bow[] list or the swords[] list?
Do I need to use MySQL along with Python? and create tables and then search the tables instead of lists?
You can create a dictionary:
weapons = {"bow": ['short', 'long', 'crossbow'], "sword": ['short', 'long']}
# prompt user and convert to lowercase (our dict consists of lowercase strings)
chooseWeapon = input('What type of weapon would you like? Bow or Sword?').lower()
if chooseWeapon in weapons: # checks if the input is one of the keys in our dict
print(f'Available {chooseWeapon}s: {weapons[chooseWeapon]}')

ML program to find the acronyms of a given list

I am researching and learning about the ML language. I have met with a question and have difficulty in solving it. I'm sure I will use the Traverse, Size and Substring functions, but i cannot put it in some way, I'm a bit confused. Could you help?
Question:
val x = [ ["National", "Aeronautics", "and", "Space", "Administration"]
, ["The", "North", "Atlantic", "Treaty", "Organization"]
]
Sample run:
val it = [ {acronym="NASA", name="National Aeronautics and Space Administration"},
, {acronym="NATO", name="The North Atlantic Treaty Organization"}
]
: nm list
Looking at the information in your question, I'm guessing that the goal of the problem is to write a function acronyms which meets the following specification. I've taken some liberty of renaming types to make it clearer:
type words = string list
type summary = {acronym : string, name : string}
val acronyms : words list -> summary list
This function takes a list of organization names (which have been split into words) and produces a list of summaries. Each summary in the output describes the corresponding organization from the input.
The tricky part is writing a function acronym : words -> summary which computes a single summary. For example,
- acronym ["National", "Aeronautics", "and", "Space", "Administration"];
val it = {acronym="NASA",name="National Aeronautics and Space Administration"}
: summary
Once you have this function, you can apply it to each organization name of the input with List.map:
fun acronyms orgs = List.map acronym orgs
I'll leave the acronym function to you. As a hint to get started, consider filtering the list of words to remove words such as "and" and "the".

Python 2.7: How to make a function print an undetermined amount of strings from a tuple

I'm making a text-based adventure game, and would like to have a universal 'look' function that uses an algorithm to tell the player how many and what objects are in a room instead of me having to write individual descriptions for each room. So it would work roughly like this:
lookround(things.bedroom)
You see:
a bed, which is the last on the right, across from Jacob's and to the left of Steve's,
and
a calendar, which is on a nail driven into the wall to the left of your bed
The objects are stored in the class 'things', which has a format that organises them with the object name first, and then the description of its location, then it repeats. That way, all the function has to do is print the first two tuples, then the next two, then the next two, and so on.
So, how would I get it to print out a number of tuples which have not been spoon fed to it?
Right now, I'm trying to use this:
def lookround(room):
print '''You see:'''
for len(room) % 2:
print ('{}, which is {},'.format(room))
The problems I'm having are that I'm getting a syntax error which points to the colon after len, and I'm not sure what I should put in .format() .
I've tried messing around with the syntax, but nothing's working.
class room(object):
things = ('a bed', 'to sleep in',
'a calendar', 'to look up the date',
'a clock', 'to wake up')
def lookround(room):
print '''You see:'''
for i in range(len(room.things)):
if not (i%2):
print ('{}, which is {},'.format(room.things[i], room.things[i+1]))
if i != len(room.things) - 2:
print 'and'
This should work with your current format. It might be a better idea to store things as a tuple of tuples, so you don't deal with the modulus business...

Applying regexp and finding the highest number in a list

I have got a list of different names. I have a script that prints out the names from the list.
req=urllib2.Request('http://some.api.com/')
req.add_header('AUTHORIZATION', 'Token token=hash')
response = urllib2.urlopen(req).read()
json_content = json.loads(response)
for name in json_content:
print name['name']
Output:
Thomas001
Thomas002
Alice001
Ben001
Thomas120
I need to find the max number that comes with the name Thomas. Is there a simple way to to apply regexp for all the elements that contain "Thomas" and then apply max(list) to them? The only way that I have came up with is to go through each element in the list, match regexp for Thomas, then strip the letters and put the remaining numbers to a new list, but this seems pretty bulky.
You don't need regular expressions, and you don't need sorting. As you said, max() is fine. To be safe in case the list contains names like "Thomasson123", you can use:
names = ((x['name'][:6], x['name'][6:]) for x in json_content)
max(int(b) for a, b in names if a == 'Thomas' and b.isdigit())
The first assignment creates a generator expression, so there will be only one pass over the sequence to find the maximum.
You don't need to go for regex. Just store the results in a list and then apply sorted function on that.
>>> l = ['Thomas001',
'homas002',
'Alice001',
'Ben001',
'Thomas120']
>>> [i for i in sorted(l) if i.startswith('Thomas')][-1]
'Thomas120'

Ocaml Error: Unbound record field label length

This is the error I'm getting and I have no idea why: "Error: Unbound record field label length "
Does anyonw know?
let rastavi str =
let sublist = ref [] in
let list = ref [] in
for i = ((str.length str)1) [down]to 0 do
if str.[i] =' ' then (str.[i] :: !sublist)
else (list := (!sublist:: !list)) sublist = []
done ;;
You're using OO notation to get the length of a string. OCaml uses functional notation. So it looks like this:
String.length str
Not like this:
str.length (* OO notation, not in OCaml *)
Edit:
Side comment: this solution is very much an imperative take on the problem. If you're trying to learn the FP mindset, you should try to think recursively and immutably. Since this looks like homework, it's very likely a functional solution is what you want.
But here are a few other problems in your original code:
You have two expressions next to each other with nothing in between. If you want to "do" two things, you need to separate them with a semicolon ; (however, this is imperative style)
You're using = which compares two values for equality. If you want to assign a value to a reference you need to use :=. (Imperative style, again.)