In today’s Programming Praxis exercise, our goal is to calculate the minimum scalar product of two vectors. Let’s get started, shall we?
A quick import:
import Data.List
Initially, I wrote a version that calculated all possible permutations and took the minimum value. After looking at the provided solution it turns out this isn’t necessary, which leads to the following shorter and more efficient version:
minScalar :: (Ord a, Num a) => [a] -> [a] -> a minScalar a = sum . zipWith (*) (sort a) . reverse . sort
A test to see if everything is working properly:
main :: IO () main = print $ minScalar [1,3,-5] [-2,4,1] == -25
Advertisements
Tags: bonsai, code, Haskell, kata, minimum, praxis, product, programming, scalar, vector
August 11, 2012 at 4:51 am |
link to programmingpraxis is broken – is relative rather than absolute
August 11, 2012 at 9:22 am |
It should be working now. Thanks for the heads up.