haskell add anything to a existing function - function

hey there using this script:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference3 a b c
| ((differenceAB < differenceBC) && (differenceBC < differenceAC)) = differenceAB
| ((differenceAB < differenceAC) && (differenceAC < differenceBC)) = differenceAB
| ((differenceBC < differenceAB) && (differenceAB < differenceAC)) = differenceBC
| ((differenceBC < differenceAC) && (differenceAC < differenceAB)) = differenceBC
| ((differenceAC < differenceBC) && (differenceBC < differenceAB)) = differenceAC
| ((differenceAC < differenceAB) && (differenceBC < differenceBC)) = differenceAC
where differenceAB
| a < b = -(a - b)
| otherwise = a - b
differenceBC
| b < c = -(b - c)
| otherwise = b - c
differenceAC
| a < c = -(a - c)
| otherwise = a - c
i can type three Integers and get the smallest result of two of these Integer´s.
but what can i do if i add one more INT, so i have:
smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d
// etc..
Should i use the "smallestDifference3"-function to get this or what do i need to do? greetings!

Introduce a generic function which takes a list, i.e.
smallestDifference :: [Int] -> Int
and then use that from your other functions, e.g.
smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d = smallestDifference [a,b,c,d]
...of course, at that point you might want to just drop those tiny functions altogether since they don't "pull their own weight".
That being said, you could implement this function more in terms of existing functions. The idea is that you need a way to get all possible pairs for the given list, then compute the difference of the pair members, and then pick the minimum of that.
You would need an 'all pairs' function like
pairs :: [a] -> [(a, a)]
pairs = concat . go
where go [] = []
go [x] = []
go (x:xs) = map (\a -> (x,a)) xs : go xs
and then you could do it like
smallestDifference = minimum
. map abs
. map (uncurry (-))
. pairs

Related

OCaml matrix manipulation

I'm looking to write an OCaml function with this structure:
rows : int list list -> char list -> int list = <fun>.
I'm having some trouble as I'm fairly new to the language.
The program should take each list and perform an operation like addition or multiplication with it's elements. For example: rows [[1;2;0];[4;5;6];[1;2;9]] [’+’;’-’;’*’];;-: int list = [3;-7;18]
Thank you in advance for any help.
Is this the basic problem? Note: I left important part for you to answer.
let nums =
[
[1;2;0];
[4;5;6];
[1;2;9];
]
let ops = ['+'; '-'; '*';]
let rec rows l o =
match (l, o) with
| ([],[]) -> []
| (hd::tl, op::tlo) ->
(
match hd with
| [] -> 0::(rows tl tlo)
| h::t -> (*The important part goes here*)
)
| _ -> failwith "Uneven list"
let ans = rows nums ops

Haskell. Assigning name to a threshold of values

I'm trying to figure out how to write in Haskell:
There is a list made of 4 variables: [w,x,y,z]
After completing the following through ghci:
collection :: Int -> Int -> Int -> Int -> [Int]
collection w x y z = [w,x,y,z]
I want to assign a "meaning" to each threshold value for w,x,y,z. Example: when 0 < x < 60, then x = "Low", when 59 < x < 80, then x = "Medium", when 79 < x < 100, then x = "High"
How do you put that in Haskell code?
If I understand correctly what you want, you can define a function that assigns what you call "meaning" to a single integer, and then map the collection list over it:
bin :: Int -> String
bin x
| x <= 0 = error "nonpositive value"
| x < 60 = "Low"
| x < 80 = "Medium"
| x < 100 = "High"
| otherwise = error "value greater than or equal to 100"
binnedCollection :: Int -> Int -> Int -> Int -> [String]
binnedCollection w x y z = map bin $ collection w x y z
For example,
Prelude> binnedCollection 0 20 60 80
["Low","Low","Medium","High"]
I have added error cases for the ranges not included in your definition; change them to whatever is appropriate for your logic.

Function to return a part of a list

I am new to Haskell and have an assignment. I have to write a
Int->Int->[u]->[u]
Function that is given input two Ints i and j and a list and returns the elements that are in possitions greater than i and smaller than j. What I have thought so far is:
fromTo :: Int->Int->[u]->[u]
fromTo i j (h:t)
|i == 1 && j == length(h:t)
= (h:t)
|i /= 1
fromTo (i-1) j t
|j /= length(h:t)
fromTo i j init(h:t)
However I get a syntax error for the second |. Also im unsure if my train of thought is correct here.
(init returns the list without its last element)
EDIT: Corrected
|i /= 1
fromTo (i-1) j (h:t)
to
|i /= 1
fromTo (i-1) j t
Fixed indentation, parenthesization, and missing =s. This reformation compiles, and works for ordinals and finite non-empty lists:
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j (h : t)
| i == 1 && j == length (h : t) = h : t
| i /= 1 = fromTo (i - 1) j t
| j /= length (h : t) = fromTo i j (init (h : t))
I think you're looking for something like this pointfree, naturally indexing span:
take :: Int -> [a] -> [a]
take _ [] = []
take 0 _ = []
take n (x : xs) = x : take (n - 1) xs
drop :: Int -> [a] -> [a]
drop _ [] = []
drop 0 xs = xs
drop n (_ : xs) = drop (n - 1) xs
span :: Int -> Int -> [a] -> [a]
span i j = drop i . take (j + 1)
which
span 0 3 [0 .. 10] == [0,1,2,3]
Or, to fit the specification:
between :: Int -> Int -> [a] -> [a]
between i j = drop (i + 1) . take j
which
between 0 3 [0 .. 10] == [1,2]
You're missing = between the | guard clause and the body. The Haskell compiler thinks the whole thing is the guard, and gets confused when it runs into the next | guard because it expects a body first. This will compile (although it is still buggy):
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j (h:t)
| i == 1 && j == length (h:t) =
(h:t)
| i /= 1 =
fromTo (i-1) j t
| j /= length (h:t) =
fromTo i j (init (h:t))
but I would say there are better ways of writing this function. For example, in principle a function like this should work on infinite lists, but your use of length makes that impossible.
Here is complete solution that use recursion:
fromTo :: Int -> Int -> [u] -> [u]
fromTo i j xs = go i j xs []
where go i j (x:xs) rs
| i < 0 || j < 0 = []
| i > length (x:xs) || j > length (x:xs) = []
| i /= 0 = go (i - 1) j t
| j /= 1 = goo i (j -1) (rs ++ [x])
| otherwise = rs
Notes:
go is standard Haskell idiom for recursive function that need extra parameters compared to main level function.
First clause make sure that negative indexes result in empty list. Second does the same for any index that exceed size of a list. Lists must be finite. Third "forgets" head of the array i times. Fourth will accumulate "next" (j - 1) heads into rs. Fifth clause will be triggered when all indexes are "spent" and rs contain result.
You could make it work on infinite lists. Drop second clause. Return rs if xs is empty before "exhausting" indexes. Then function will take "up to" (j-1) elements from i.

Pattern match a function in F#

I have an maybe unusual question, but how does one match a function in F# using pattern matching?
Imagine the following:
I have multiple function signatures, which will be used multiple times, like:
binary function: int -> int -> int
unary function: int -> int
boolean function: int -> int -> bool
...
Now imagine the function evaluate, which itself takes a function f. The signature of f must be one of the listed above.
How do I match such a case?
I have tried the following things:
Test No.1 : Using delegates and Unions:
type UnaryFunction = delegate of int -> int
type BinaryFunction = delegate of (int -> int) -> int
type BooleanFunction = delegate of (int -> int) -> bool
type Functions =
| Unary of UnaryFunction
| Binary of BinaryFunction
| Boolean of BooleanFunction
// ...
let evaluate f = // signature: Functions -> string
match f with
| Unary u ->
let test_result = u.Invoke 3
sprintf "the result of the unary function is %d" test_result
| Binary b ->
let test_result = b.Invoke 315 42
sprintf "the result of the binary function is %d" test_result
| Boolean o ->
let test_result = o.Invoke 315 42
if test_result then "yeah" else "nope"
Test No.2 : Using type pattern matching and delegates:
type UnaryFunction = delegate of int -> int
type BinaryFunction = delegate of (int -> int) -> int
type BooleanFunction = delegate of (int -> int) -> bool
let evaluate f =
match f with
| ?: UnaryFunction as u ->
let test_result = u.Invoke 3
sprintf "the result of the unary function is %d" test_result
| ?: BinaryFunction as b ->
let test_result = b.Invoke 315 42
sprintf "the result of the binary function is %d" test_result
| ?: BooleanFunction as o ->
let test_result = o.Invoke 315 42
if test_result then "yeah" else "nope"
| _ -> "invalid function type"
The problem with these examples is, that delegates of ... will be matched instead of actual functions.
I would like to see somethink like this:
let evaluate f =
match f with
| ?: (int -> int) as u ->
let test_result = u 3
sprintf "the result of the unary function is %d" test_result
| ?: ((int -> int) -> int) as b ->
let test_result = b 315 42
sprintf "the result of the binary function is %d" test_result
| ?: ((int -> int) -> bool) as o ->
let test_result = o 315 42
if test_result then "yeah" else "nope"
| _ -> "invalid function type"
Does F# has a special syntax for function pattern matching?
And if not, why so? Am I missing something, or isn't it also important to be able to match functions just as anything else, as this is a functional language?
Instead of using delegates, just define the work using functions directly:
type UnaryFunction = int -> int
type BinaryFunction = int -> int -> int
type BooleanFunction = int -> int -> bool
type Functions =
| Unary of UnaryFunction
| Binary of BinaryFunction
| Boolean of BooleanFunction
// ...
let evaluate f = // signature: Functions -> string
match f with
| Unary u ->
let test_result = u 3
sprintf "the result of the unary function is %d" test_result
| Binary b ->
let test_result = b 315 42
sprintf "the result of the binary function is %d" test_result
| Boolean o ->
let test_result = o 315 42
if test_result then "yeah" else "nope"
Once you've done this, you can call them as needed (as below, showing FSI output):
> evaluate (Unary (fun x -> x + 3));;
val it : string = "the result of the unary function is 6"
> let someBinaryFunction x y = x * y;;
val someBinaryFunction : x:int -> y:int -> int
> Binary someBinaryFunction |> evaluate;;
val it : string = "the result of the binary function is 13230"

Call comparison operators in Haskell

i need to find out if the difference from differenceAB is the smallest:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference a b c
| differenceAB < differenceBC < differenceAC = differenceAB
| otherwise = differenceAB
where differenceAB
| a < b = -(a - b)
| otherwise = a - b
differenceBC
| b < c = -(b - c)
| otherwise = b - c
differenceAC
| a < c = -(a - c)
| otherwise = a - c
but i get this error:
cannot mix `<' [infix 4] and `<' [infix 4] in the same infix expression
how to solve my problem? anybody know´s? greetingS!
There are a couple of problems here.
You have 3 exactly identical functions. Probably you want values:
smallestDifference a b c = ....
where
diffAC = abs(a-c)
diffAB = abs(a-b)
diffBC = abs(b-c)
Now for the expression, you can't write
diffAC < diffAB < diffBC
since (<) is a non-associative operator. Which means you must write explicit parentheses:
(diffAC < diffAB) < diffBC
But this doesnt type check, because for the second (<) the left hand side is Bool, but the right hand side is Int. What you want is
(diffAC < diffAB) && (diffAB < diffBC)
i.e. if ac is lower then ab and ab is lower than bc
If you just want to find the smallest difference, following will work.
smallestdiff a b c = minimum [abs $ a-b, abs $ b-c, abs $a-c]
There is no such thing as chaining operators in Haskell. You should use explicit logical operations:
smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference a b c
| (differenceAB < differenceBC) && (differenceBC < differenceAC) = differenceAB
| otherwise = differenceAB
BTW, your code is weird, you return differenceAB from both guard clauses. It is not clear what you want to achieve, so I cannot help further.