Skip to content

Instantly share code, notes, and snippets.

@Nexmean
Last active December 25, 2019 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nexmean/56c98ff9563ff25a05b70512a7de6848 to your computer and use it in GitHub Desktop.
Save Nexmean/56c98ff9563ff25a05b70512a7de6848 to your computer and use it in GitHub Desktop.
-- пример полиморфной рекурсии, который невозможно скомпилировать без универсального представления данных в рантайме
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