I have to write a function sum that takes as first argument a value n. The second argument is a function f so that sum calculates the Gaussian sum.
In a second step, I have to implement thesum_gauss (int->int) using sum and a lambda expression.
This is my idea for the function sum:
let rec sum (n:int) (f:int->int) : int =
if n < 1 then 0
else sum (n-1) f + f n
And this is sum_gauss which throws an error:
let sum_gauss = sum ((i:int) -> fun (i:int) : int -> i)
The error is:
Line 1, characters 30-32:
Error: Syntax error: ')' expected
Line 1, characters 22-23:
This '(' might be unmatched
I don't understand why this error is raised because every left bracket is matched by a right bracket.
Rewriting with type inference cleaning things up:
let rec sum n f =
if n < 1 then 0
else sum (n-1) f + f n
If you wish to add all number from 1 to n. you need to pass the number and the function to sum_gauss as separate arguments.
let sum_gauss n = sum n (fun x -> x)
Of course, fun x -> x is really just Fun.id.
let sum_gauss n = sum n Fun.id
If you feel like being extra clever and you're already using the Fun module you can use Fun.flip to pass Fun.id as the second argument of sum and elide n from the definition entirely. The fact that sum is not polymorphic avoids weak typing issues with partial application.
let gauss_sum = Fun.(flip sum id)
Related
I am working on the following exercise:
Define a function libDiv which computes the list of natural divisors of some positive integer.
First define libDivInf, such that libDivInf n i is the list of divisors of n which are lesser than or equal to i
libDivInf : int -> int -> int list
For example:
(liDivInf 20 4) = [4;2;1]
(liDivInf 7 5) = [1]
(liDivInf 4 4) = [4;2;1]
Here's is my attempt:
let liDivInf : int -> int -> int list = function
(n,i) -> if i = 0 then [] (*ERROR LINE*)
else
if (n mod i) = 0 (* if n is dividable by i *)
then
i::liDivInf n(i-1)
else
liDivInf n(i-1);;
let liDiv : int -> int list = function
n -> liDivInf n n;;
I get:
ERROR: this pattern matches values of type 'a * 'b ,but a pattern
was expected which matches values of type int
What does this error mean? How can I fix it?
You've stated that the signature of liDivInf needs to be int -> int -> int list. This is a function which takes two curried arguments and returns a list, but then bound that to a function which accepts a single tuple with two ints. And then you've recursively called it in the curried fashion. This is leading to your type error.
The function keyword can only introduce a function which takes a single argument. It is primarily useful when you need to pattern-match on that single argument. The fun keyboard can have multiple arguments specified, but does not allow for pattern-matching the same way.
It is possible to write a function without using either.
let foo = function x -> x + 1
Can just be:
let foo x = x + 1
Similarly:
let foo = function x -> function y -> x + y
Can be written:
let foo x y = x + y
You've also defined a recursive function, but not included the rec keyword. It seems you're looking for something much more like the following slightly modified version of your attempt.
let rec liDivInf n i =
if i = 0 then
[]
else if (n mod i) = 0 then
i::liDivInf n (i-1)
else
liDivInf n (i-1)
I am trying to learn Haskell programming language by trying to figure out some pieces of code.
I have these 2 small functions but I have no idea how to test them on ghci.
What parameters should I use when calling these functions?
total :: (Integer -> Integer) -> Integer -> Integer
total function count = foldr(\x count -> function x + count) 0 [0..count]
The function above is supposed to for the given value n, return f 0 + f 1 + ... + f n.
However when calling the function I don't understand what to put in the f part. n is just an integer, but what is f supposed to be?
iter :: Int -> (a -> a) -> (a -> a)
iter n f
| n > 0 = f . iter (n-1) f
| otherwise = id
iter' :: Int -> (a -> a) -> (a -> a)
iter' n = foldr (.) id . replicate n
This function is supposed to compose the given function f :: a -> a with itself n :: Integer times, e.g., iter 2 f = f . f.
Once again when calling the function I don't understand what to put instead of f as a parameter.
To your first question, you use any value for f such that
f 0 + f 1 + ... + f n
indeed makes sense. You could use any numeric function capable of accepting an Integer argument and returning an Integer value, like (1 +), abs, signum, error "error", (\x -> x^3-x^2+5*x-2), etc.
"Makes sense" here means that the resulting expression has type ("typechecks", in a vernacular), not that it would run without causing an error.
To your second question, any function that returns the same type of value as its argument, like (1+), (2/) etc.
I'm trying to make program which counts the number of odd digits in integer using Haskell. I have ran into problem with checking longer integers. My program looks like this at the moment:
oddDigits:: Integer -> Int
x = 0
oddDigits i
| i `elem` [1,3,5,7,9] = x + 1
| otherwise = x + 0
If my integer is for example 22334455 my program should return value 4, because there are 4 odd digits in that integer. How can I check all numbers in that integer? Currently it only checks first digit and returns 1 or 0. I'm still pretty new to haskell.
You can first convert the integer 22334455 to a list "22334455". Then find all the elements satisfying the requirement.
import Data.List(intersect)
oddDigits = length . (`intersect` "13579") . show
In order to solve such problems, you typically split this up into smaller problems. A typical pipeline would be:
split the number in a list of digits;
filter the digits that are odd; and
count the length of the resulting list.
You thus can here implement/use helper functions. For example we can generate a list of digits with:
digits' :: Integral i => i -> [i]
digits' 0 = []
digits' n = r : digits' q
where (q, r) = quotRem n 10
Here the digits will be produced in reverse order, but since that does not influences the number of digits, that is not a problem. I leave the other helper functions as an exercise.
Here's an efficient way to do that:
oddDigits :: Integer -> Int
oddDigits = go 0
where
go :: Int -> Integer -> Int
go s 0 = s
go s n = s `seq` go (s + fromInteger r `mod` 2) q
where (q, r) = n `quotRem` 10
This is tail-recursive, doesn't accumulate thunks, and doesn't build unnecessary lists or other structures that will need to be garbage collected. It also handles negative numbers correctly.
This question already has answers here:
Haskell operator vs function precedence
(5 answers)
Closed 4 years ago.
I'm doing Project Euler with Haskell, and found something to learn when completing the very first problem. Here's my code:
isValid x = (mod x 3 == 0) || (mod x 5 == 0)
listValid :: Integer -> [Integer]
listValid n = [x | x <- [1..n-1], isValid x]
The function listValid will get all the positive integers less than n that are divisble by either 3 or 5. Easy enough.
*Main> listValid 10
[3,5,6,9]
Now I need to sum them. I figure the sum function is the right way to do this. What I don't understand is why the first two versions work, and then third doesn't.
*Main> sum (listValid 10)
23
*Main> sum $ listValid 10
23
*Main> sum listValid 10
<interactive>:4:5:
Couldn't match type ‘[Integer]’ with ‘a0 -> t’
Expected type: Integer -> a0 -> t
Actual type: Integer -> [Integer]
Relevant bindings include it :: t (bound at <interactive>:4:1)
In the first argument of ‘sum’, namely ‘listValid’
In the expression: sum listValid 10
Is this an order of operations problem, where I need to wrap in parentheses to assert which function should be applied first? And if so, what is the $ doing in the second version?
It's about associativity. Function application is left-associative, so sum listValid 10 is equivalent to (sum listValid) 10, not sum (listValid 10). And if you think about it, it has to be that way: If you define add x y = x+y, you wouldn't want add 1 2 to be equivalent to add (1 2).
So the issue here is that in sum listValid 10, it doesn't see listValid 10 as the argument to sum; it sees listValid as the argument to sum and then 10 as the argument to sum listValid.
$ resolves this issue because it's an infix operator and it's perfectly clear that sum is its left operand and listValid 10 is its right operand (keeping in mind that function application has higher precedence than any infix operator, so it can't be seen as (sum $ listValid) 10).
Function application f x is the highest-priority operation (and left-associative), so that
sum listValid 10
is equivalent to (sum listValid) 10.
The $ operator, on the other hand, has the lowest precedence possible (and is right-associative, although that isn't relevant here), so that
sum $ listValid 10
is implicitly the same as sum $ (listValid 10), not (sum $ listValid) 10. Thus, it is commonly used to eliminate parentheses.
When you write f $ x, you write in fact ($) f x, with ($) :: (a -> b) -> a -> b a function. This function is defined as:
($) :: forall r a (b :: TYPE r). (a -> b) -> a -> b
f $ x = f x
The above does not look very impressive. If you thus write f $ x, it is equivalent to f x, so then why write a $ anyway? Because this operator has precedence 0. It thus means that if you write:
f $ x+2
it is interpreted as:
($) f (x+2)
and thus:
f (x+2)
without the need to write brackets.
Going back to your question, if you write:
sum $ listValid 10
this is parsed as:
($) (sum) (listValid 10)
and thus functionally equivalent to:
sum (listValid 10)
If you however write:
sum listValid 10
Haskell interprets this as:
(sum listValid) 10
now the sum of a function with type Integer -> [Integer] does not make sense, sum :: Num a => [a] -> a should take a list of Numerical values, hence the error.
Function application is left-associative, so
f x y
is parsed as:
(f x) y
However, function application has higher precedence than any infix operator, so
f x $ g y
is parsed as:
(f x) $ (g y)
In particular, you have:
sum listValid 10 = (sum listValid) 10
sum $ listValid 10 = sum $ (listValid 10) = sum (listValid 10)
I'm reviewing an old exam in my Haskell programming course and I can't seem to wrap my head around this function (I think there is just too little information given).
The code given is
myId x = x
function n f
| n > 0 = f . function (n-1) f
| otherwise = myId
I know that if I for example call the function with the input 2 (*2), I will get a function as result. And if I call it with (-2) (*2) 1 I will get the result 1.
I just don't know how? Also I can't wrap my head around the typecast of the function.
I know that these two options are correct but I don't understand why (probably parentheses that confuse me at the moment).
function :: (Num a, Ord a) => a -> (a -> a) -> a -> a
function :: (Num a, Ord b) => a -> (b -> b) -> b -> b
Anyone that can clarify how I should "read" this function and how I should understand how the typecast works (been reading my Programming in Haskell literature and from Learn You a Haskell but been going in circle for a few days now).
function takes some number n and a function f :: a -> a, and composes that function with itself n times, returning another function of type a -> a. When the returned function is applied to a value of type a, the result is essentially the same as executing f in a loop n times, using the output of each previous step as the input for the next.
Perhaps it is easier to see the similarity if the final parameter is made explicit:
function :: (Ord a, Num a) -> a -> (b -> b) -> b -> b
function n f x
| n > 0 = f (function (n-1) f x)
| otherwise = x
This is functionally equivalent to your point-free function.
In Haskell, a function f :: a -> b -> c can be interpreted either as "a function that takes an a and a b and returns a c" or "a function that takes an a and returns a function from b to c". When you apply a function to one or more inputs, think of each input as eliminating one of the function's arguments. In this instance, function 10 returns a new function with type (a -> a) -> a -> a, and function 2 (*2) returns a function with type Num a => a -> a.
When you think of it this way, it should hopefully be clear why function (-2) (*2) 1 returns a number while function 2 (*2) returns a function. There is no type casting going on; when you are applying the three argument function to two inputs, you get another function back instead of a value, since you didn't provide the final input needed to compute that value.