美文网首页
Hylang tutorial

Hylang tutorial

作者: SmalltalkVoice | 来源:发表于2017-08-26 15:11 被阅读47次

    change list value

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    plyaers[0] = 'Half' 
    
    (setv players  ["charles", "martina", "michael", "florence", "eli"])
    (setv (get players 0) "ducati") # method 1
    (setv (.  players [0]) "ducati") # method 2
    (.__setitem__  players  0 "ducati") # method 3
    (assoc players 0 "ducati") #method 4
    

    slice list

    >>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
    >>> players[1:3]
    ['martina', 'michael']
    
    => (setv players ["charles"  "martina"  "michael"  "florence"  "eli"])
    => (cut players 1 3)
    ['martina', 'michael']
    

    copy list

    >>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
    >>> copy_player = players[:]
    >>> copy_player
    ['charles', 'martina', 'michael', 'florence', 'eli']
    
    => (setv players ["charles"  "martina"  "michael"  "florence"  "eli"])
    => (setv copy_player (list-comp x [x players]))
    => copy_player
    ['charles', 'martina', 'michael', 'florence', 'eli']
    

    if statement

      cars = ['audi', 'bmw', 'subaru', 'toyota']
      for car in cars:
         if car == 'bmw':
              print(car.upper())
          else:
              print(car.title())
    
    (setv cars ["audi" "bmw" "subaru" "toyota"])
    (for [car cars]
        (if (= car "bmw")
            (print (.upper car)) ;;True
            (print (.title car)) ;;False
            ))
    

    dictionary

    >>> alien_0 = {'color': 'green', 'points': 5}
    >>> alien_0['color']
    'green'
    >>> alien_0['x'] = 0
    >>> alien_0['y'] = 25
    >>> alien_0
    {'y': 25, 'color': 'green', 'points': 5, 'x': 0}
    >>> alien_0['x'] = 13
    >>> del alien_0['x']
    >>> alien_0
    {'y': 25, 'color': 'green', 'points': 5}
    
    
    => (setv alien_0 {"color" "green" "points" 5})
    => (get alien_0 "color")
    'green'
    => (assoc alien_0 "x" 0)
    => (assoc alien_0 "y" 25)
    => alien_0
    {'points': 5, 'y': 25, 'color': 'green', 'x': 0}
    => (assoc alien_0 "x" 13)
    => (del (get alien_0 "x"))
    => alien_0
    {'points': 5, 'y': 25, 'color': 'green'}
    

    travel dictionary

    >>> alien_0 = {"color": "green" ,"points": 5}
    >>> for i in alien_0:
    ...   print(i,alien_0[i])
    ...
    color green
    points 5
    
    (setv alien_0 {"color" "green" "points" 5})
    (for [key alien_0]
        (print key (get alien_0 key)))
    
    

    input

    >>> age = int(input("How old are you?"))
    How old are you?12
    >>> age
    12
    >>> type(age)
    <class 'int'>
    
    =>  (setv age (int (input "How old are you?")))
    How old are you?12
    => age
    12
    => (type age)
    <class 'int'>
    

    while

    prompt = "\nPlease enter the name of a city you have visited:"
    prompt += "\n(Enter 'quit' when you are finished.) "
    while True:
        city = input(prompt)
        if city == 'quit':
            break
        else:
            print("I'd love to go to " + city.title() + "!")
    
    (setv prompt "Please enter the name of a city you have visited:")
    (+ prompt "\n(Enter 'quit' when you are finished.) " )
    (while True
        (setv city (input prompt))
        (if (= city "quit")
            (break)
            (print "I'd love to go to " (.title city) "!")))
    
    

    define function

    pizza.py
    def make_pizza(size,*toppings):
        print("\nMaking a " + str(size) +
            "-inch pizza with the following toppings:")
        for topping in toppings:
            print("- " + topping)
    
    making_pizzas.py
    import pizza
    pizza.make_pizza(16,'pepperoni')
    pizza.make_pizza(12,'mushrooms','green_peppers','extra_cheese')
    
    
    pizza.hy
    (defn make_pizza [size &rest toppings]
        (print "\nMaking a " (str size) 
          "-inch pizza with the following toppings:")
        (for [topping toppings]
            (print topping)))
    
    making_pizzas.hy
    (import pizza)
    (.make_pizza pizza 16 "pepperoni" "中华街") ;;特意添加了一个中文
    (.make_pizza pizza 12 "mushrooms" "green_peppers" "extra_cheese")
    

    define class

    class Dog():
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def sit(self):
            print(self.name.title() + " is now sitting.")
    
        def roll_over(self):
            print(self.name.title() + " rolled over!")
    
    
    my_dog = Dog('willie',6)        
    print("My dog's name is " + my_dog.name.title() + ".")
    print("My dog's is " + str(my_dog.age) + " years old.")
    
    
    (defclass Dog [object]
        (defn --init-- [self name age]
            (setv self.name name)
            (setv self.age age))
        (defn sit [self]
            (print (.title self.name) " is now sitting"))
        (defn roll_over(self)
            (print (.title self.name " rolled over!"))))
    
    (setv my_dog (Dog "willie" 6))
    (print "My dog's name is " (.title my_dog.name) ".")
    (print "My dog's is " (str my_dog.age) " years old.")
    

    import module

    from collection import OrderedDict
    fk = OrederedDict()
    fk['jen'] = "python"
    fk['sarah'] = 'c'
    fk['edward'] = 'ruby'
    fk['phil'] = 'python'
    print(fk)
    
    => (import [collections [OrderedDict]])
    => (setv fk (OrderedDict))
    => (assoc fk "jen" "python")
    => (assoc fk "sarah" "c")
    => (assoc fk "edward" "ruby")
    => (assoc fk "phil" "python")
    => fk
    OrderedDict([('jen', 'python'), ('sarah', 'c'), ('edward', 'ruby'), ('phil', 'python')])
    

    read file

    pi_digits.txt

    3.1415926535
    8979323846
    2643383279

    file_reader.py
    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        for line in file_object:
            print(line.rstrip())
    
    file_reader.hy
    (setv filename "pi_digits.txt")
    (with [file_object (open filename)]
        (for [line file_object]
            (print (.rstrip line))))
    

    try_except_else

    alice.txt
    Alice is the main character of the story “Alice’s Adventures in Wonderland” and the sequel “Through the Looking Glass and what Alice found there”.
    
    She is a seven-year-old English girl with lots of imagination and is fond of showing off her knowledge. Alice is polite, well raised and interested in others, although she sometimes makes the wrong remarks and upsets the creatures in Wonderland. She is easily put off by abruptness and rudeness of others.
    
    In Through the Looking Glass, she is 6 months older and more sure of her identity.
    
    word_count.py
    def count_words(filename):
         """计算一个文件大致包含多少个单词"""
          try:
              with open(filename) as f_obj:
                  contents = f_obj.read()
          except FileNotFoundError:
              msg = "Sorry, the file " + filename + " does not exist."
              print(msg)
          else:
              # 计算文件大致包含多少个单词
              words = contents.split()
              num_words = len(words)
              print("The file " + filename + " has about " + str(num_words) +
                  " words.")
    
    filename = 'alice.txt'
    count_words(filename)
    
    word_count.hy
    (defn count_words [filename]
        (try
            (with [f_obj (open filename "rb")]
                (setv contents (.read f_obj)))
            (except [FileNotFoundError]
                (setv msg (+ "Sorry,the file " filename " does not exist"))
                (print msg))
            (else
                (setv words (.split contents))
                (setv num_words (len words))
                (print "The file" filename " has about " (str num_words) " words"))))
    (setv filename "alice.txt")
    (count_words filename)
    

    相关文章

      网友评论

          本文标题:Hylang tutorial

          本文链接:https://www.haomeiwen.com/subject/fbomdxtx.html