logic.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Natural Language Toolkit: Combinatory Categorial Grammar
  2. #
  3. # Copyright (C) 2001-2019 NLTK Project
  4. # Author: Tanin Na Nakorn (@tanin)
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. """
  8. Helper functions for CCG semantics computation
  9. """
  10. from nltk.sem.logic import *
  11. def compute_type_raised_semantics(semantics):
  12. core = semantics
  13. parent = None
  14. while isinstance(core, LambdaExpression):
  15. parent = core
  16. core = core.term
  17. var = Variable("F")
  18. while var in core.free():
  19. var = unique_variable(pattern=var)
  20. core = ApplicationExpression(FunctionVariableExpression(var), core)
  21. if parent is not None:
  22. parent.term = core
  23. else:
  24. semantics = core
  25. return LambdaExpression(var, semantics)
  26. def compute_function_semantics(function, argument):
  27. return ApplicationExpression(function, argument).simplify()
  28. def compute_composition_semantics(function, argument):
  29. assert isinstance(argument, LambdaExpression), (
  30. "`" + str(argument) + "` must be a lambda expression"
  31. )
  32. return LambdaExpression(
  33. argument.variable, ApplicationExpression(function, argument.term).simplify()
  34. )
  35. def compute_substitution_semantics(function, argument):
  36. assert isinstance(function, LambdaExpression) and isinstance(
  37. function.term, LambdaExpression
  38. ), ("`" + str(function) + "` must be a lambda expression with 2 arguments")
  39. assert isinstance(argument, LambdaExpression), (
  40. "`" + str(argument) + "` must be a lambda expression"
  41. )
  42. new_argument = ApplicationExpression(
  43. argument, VariableExpression(function.variable)
  44. ).simplify()
  45. new_term = ApplicationExpression(function.term, new_argument).simplify()
  46. return LambdaExpression(function.variable, new_term)