Functional Data Types in Python

For those who have spent some time with sml, ocaml, haskell, etc., when you return to using C, Python, Java, etc., you begin to notice that you never knew. I do some things in Python and I realized what I really want is a data type with a functional style like (for example)

datatype phoneme = Vowel of string | Consonant of voice * place * manner
datatype voice = Voiced | Voiceless
datatype place = Labial | Dental | Retroflex | Palatal | Velar | Glottal
datatype manner = Stop | Affricate | Fricative | Nasal | Lateral
type syllable = phoneme list

Does anyone have a special way to simulate this in Python?

+3
source share
3 answers

As stated above, your types of voice, place, and type are simply enumerated types. There are several ways to implement features such as

class voice(object):
  Voiced, Voiceless = range(2)

Then you can turn to the voice. Vocal and voice. Untimely, etc.

, . C - . - python . , . - Vowel Consonant. ++ - Vowel Consonant; python , , , , .

,

class Vowel(object):
  def SomeInitialMethod(self):
    # ...

class Consonant(object):
  def SomeInitialMethod(self):
    # ...

p.SomeInitialMethod() # p can be either vowel or consonant

def SomeLaterFunction(p)
  # p is assumed to be either a Vowel or a Consonant
  if isinstance(p, Vowel):
    # ...
  elif isinstance(p, Consonant):
    # ...
+1

voice, place manner :

class Enum(object):
   def __init__(self, *values):
      self._values = set(values)
      for value in values:
         setattr(self, value, value)
   def __iter__(self):
      return iter(self._values)

place = Enum('Labial', 'Dental', 'Retroflex', 'Palatal', 'Velar', 'Glottal')

a = place.Retroflex    
if a == place.Labial:
   print "How did this happen?"

for p in place:
   print "possible value:", p
+1

, .

class Phoneme:
    # ...

class Consonant(Phoneme):
    def __init__(self, voice, place, manner):
        self.voice = voice
        self.place = place
        self.manner = manner
    # ...

h = Consonant('Voiceless', 'Glottal', 'Fricative')
# ...
0

Source: https://habr.com/ru/post/1740408/


All Articles