How to resolve the algorithm Constrained genericity step by step in the Icon and Unicon programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Constrained genericity step by step in the Icon and Unicon programming language

Table of Contents

Problem Statement

Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Constrained genericity step by step in the Icon and Unicon programming language

Source code in the icon programming language

import Utils        # From the UniLib package to get the Class class.

class Eatable:Class()
end

class Fish:Eatable(name)
    method eat(); write("Eating "+name); end
end

class Rock:Class(name)
    method eat(); write("Eating "+name); end
end

class FoodBox(A)
initially
    every item := !A do if "Eatable" == item.Type() then next else bad := "yes" 
    return /bad
end

procedure main()
    if FoodBox([Fish("salmon")]) then write("Edible") else write("Inedible")
    if FoodBox([Rock("granite")]) then write("Edible") else write("Inedible")
end


  

You may also check:How to resolve the algorithm Sockets step by step in the J programming language
You may also check:How to resolve the algorithm Discordian date step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Define a primitive data type step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Anagrams step by step in the ARM Assembly programming language
You may also check:How to resolve the algorithm Hash join step by step in the AppleScript programming language