Declare type list argument in F# -


i building simple function compares 2 lists , returns true if first list prefix of second one. expected signature:

prefix: int list -> int list -> bool 

for example:

prefix [1; 2] [1; 2; 3; 4] --> true prefix [ ] [1;2] --> true prefix [2] [1;2;3] --> false 

right now, @ step:

let prefix l1 l2 =         match l1         | (l1, l2) when (l1.[0] = l2.[0]) -> true         | _ -> false  

i think on right way, got error:

 operator 'expr.[idx]' has been used on object of     indeterminate type based on information prior program point. consider adding      further type constraints 

how can declare in prefix l1 , l2 lists? looked solution here problem trivial there not answer.

to answer last part of question declaring types lists (since other parts answered already), use "type annotations". (name : type) in function argument, such as

let prefix (l1 : _ list) (l2 : _ list) = ... 

that declare both l1 , l2 lists of type compiler infer. can replace _ specific or generic type too, see fit.

for implementing function hand, remember you'll have go further comparing first element - you'll need recurse through lists.

let prefix l1 l2 =     let rec loop = function         | [], _ -> true         | _, [] -> false         | h1 :: _, h2 :: _ when h1 <> h2 -> false         | _ :: t1, _ :: t2 -> loop (t1, t2)     loop (l1, l2) 

this version not need type annotations @ all, because pattern matches inside loop constrain both arguments of type 'a list. if wanted function explicitly int lists, though, instead start with

let prefix (l1 : int list) l2 = 

you need annotate 1 argument, because other constrained of same type.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -