Last active
December 25, 2019 21:42
-
-
Save kremovtort/56c98ff9563ff25a05b70512a7de6848 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- пример полиморфной рекурсии, который невозможно скомпилировать без универсального представления данных в рантайме | |
import System.IO | |
class ScalarProduct a where | |
scalarProduct :: a -> a -> Integer | |
data Nil = Nil | |
data Cons a = Cons Integer a | |
instance ScalarProduct Nil where | |
scalarProduct Nil Nil = 0 | |
instance ScalarProduct a => ScalarProduct (Cons a) where | |
scalarProduct (Cons i1 a1) (Cons i2 a2) = i1 * i2 + scalarProduct a1 a2 | |
main'' :: ScalarProduct a => Integer -> Integer -> a -> a -> Integer | |
main'' 0 _ first second = scalarProduct first second | |
main'' n i first second = main'' (n-1) (i+1) (Cons (2*i+1) first) (Cons (i*i) second) | |
main' :: Integer -> Integer | |
main' n = main'' n 0 Nil Nil | |
main :: IO () | |
main = do | |
putStr "Enter a number: " *> hFlush stdout | |
n <- readLn | |
putStrLn $ show $ main' n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment